Jump to content

Search the Community

Showing results for tags 'mysqli'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • W3Schools
    • General
    • Suggestions
    • Critiques
  • HTML Forums
    • HTML/XHTML
    • CSS
  • Browser Scripting
    • JavaScript
    • VBScript
  • Server Scripting
    • Web Servers
    • Version Control
    • SQL
    • ASP
    • PHP
    • .NET
    • ColdFusion
    • Java/JSP/J2EE
    • CGI
  • XML Forums
    • XML
    • XSLT/XSL-FO
    • Schema
    • Web Services
  • Multimedia
    • Multimedia
    • FLASH

Calendars

  • Community Calendar

Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Languages

Found 16 results

  1. The CodexWorld DB Class

    <?php /* * DB Class * This class is used for database related (connect, insert, update, and delete) operations * @author CodexWorld.com * @url http://www.codexworld.com * @license http://www.codexworld.com/license */ class DB{ private $dbHost = "..."; private $dbUsername = "..."; private $dbPassword = "..."; private $dbName = "..."; public function __construct(){ if(!$this->db){ // Connect to the database $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); if($conn->connect_error){ die("Failed to connect with MySQL: " . $conn->connect_error); }else{ $this->db = $conn; } } } /* * Returns rows from the database based on the conditions * @param string name of the table * @param array select, where, order_by, limit and return_type conditions */ public function getRows($table,$conditions = array()){ $sql = 'SELECT '; $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*'; $sql .= ' FROM '.$table; if(array_key_exists("where",$conditions)){ $sql .= ' WHERE '; $i = 0; foreach($conditions['where'] as $key => $value){ $pre = ($i > 0)?' AND ':''; $sql .= $pre.$key." = '".$value."'"; $i++; } } if(array_key_exists("order_by",$conditions)){ $sql .= ' ORDER BY '.$conditions['order_by']; } if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){ $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){ $sql .= ' LIMIT '.$conditions['limit']; } $result = $this->db->query($sql); if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){ switch($conditions['return_type']){ case 'count': $data = $result->num_rows; break; case 'single': $data = $result->fetch_assoc(); break; default: $data = ''; } }else{ if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $data[] = $row; } } } return !empty($data)?$data:false; } } $test = new DB(); if ($test instanceof DB) { echo 'Instantiated'; } else { echo 'Uninstantiated. Include failed.'; } $conditions = []; $tbl_name = 'rss2_podcast_item'; $test->getRows($tbl_name, $conditions); function getRows($mysqli_obj, $table,$conditions = array()){ $sql = 'SELECT '; $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*'; $sql .= ' FROM '.$table; if(array_key_exists("where",$conditions)){ $sql .= ' WHERE '; $i = 0; foreach($conditions['where'] as $key => $value){ $pre = ($i > 0)?' AND ':''; $sql .= $pre.$key." = '".$value."'"; $i++; } } if(array_key_exists("order_by",$conditions)){ $sql .= ' ORDER BY '.$conditions['order_by']; } if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){ $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){ $sql .= ' LIMIT '.$conditions['limit']; } $result = $mysqli_obj->query($sql); if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){ switch($conditions['return_type']){ case 'count': $data = $result->num_rows; break; case 'single': $data = $result->fetch_assoc(); break; default: $data = ''; } }else{ if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $data[] = $row; } } } return !empty($data)?$data:false; } ?> <?php $tbl_name = 'rss2_podcast_item'; $conditions = []; print_r(getRows($mysqli_obj,$tbl_name,$conditions)); ?> Please find above two sets of code and a quoted error message from the first set. The first set of code is a portion of a PHP class called DB. The second set of code is extracted from the first and modified in order to test the integrity of the function. At the bottom of each block of code is included the code necessary to call the getRows() method/function. Whereas the method of the class fails, the extracted function does not. In both cases the same database and table are accessed with success. I am suspicious of the way in which the class is constructed. I have tried several modifications, but none of them appear to work. Roddy
  2. connecting to msqli

    Looking at how form items are put into a mysql table, the part that seems daunting is if ones form has like 50 items... having to list all those IDs with their variables makes me wonder if there is a better way or if its just " it up buttercup.".
  3. Hello. I'd like to request a little guidance with regards forms and updating a database table please. I've created a form which has a dropdown list. I'd just like to enquire:- 1. How do I pass the selected result from the dropdown list to a variable? (at present I've written:- $user_gender = $_POST["profile_gender"] 2. I'm unable to update the database table. The database opens and there's no errors reported. I'd just like to ask the following looks ok? $sql = "UPDATE registration_table SET Gender='$user_gender' WHERE Member_id='$userID'"; Thank You.
  4. I don't know how to use "mysqli_result()" function, with general arguments. In "mysql_result()" function, it was like this :- "mysql_result($query, 'row', 'feild')". Here First argument is the "query", Second argument is the specific "row" in the database, Third argument is the "field name" of the row. I don't know if the arguments are same for "mysqli_result()" or not, or maybe more arguments are included or excluded!!!! Hey, I noticed the same question has been asked by so many different members!! in the Forum. Focusing to different use. But one more thing I noticed that the actual implementation is not here, Like "mysqli_result('argument1', 'argument2', 'argument3');". Basically the implementation is quite simple, but heres the confusion thing, and thats the correct arguments, as I've show in most upper example!!?
  5. "Require_once" produces "undefined variable"

    Hi guys! I have a little problem and it's that I get an error in a determined function where I call my connection and I don't know why. The errors are: 1) Notice: Undefined variable: conexionidiomas in C:\wamp64\www\idiomas\preguntas-frecuentes.php on line 10 2) Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp64\www\idiomas\preguntas-frecuentes.php on line 11 This is what I have from "/Connections/conexionidiomas.php": # FileName="Connection_php_mysql.htm" # Type="MYSQL" # HTTP="true" $hostname_conexionidiomas = "p:localhost:3307"; $database_conexionidiomas = "idiomasbd"; $username_conexionidiomas = "root"; $password_conexionidiomas = "asdasdf"; $conexionidiomas = mysqli_connect($hostname_conexionidiomas, $username_conexionidiomas, $password_conexionidiomas, $database_conexionidiomas); and this in "preguntas-frecuentes.php": <?php require_once('Connections/conexionidiomas.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($conexionidiomas, $theValue) : mysqli_escape_string($conexionidiomas,$theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO tblfrecuentes (strPregunta,fchFecha) VALUES (%s,NOW())",GetSQLValueString($_POST['strPregunta'], "text")); $Result1 = mysqli_query($conexionidiomas,$insertSQL) or die(mysqli_error($conexionidiomas)); } ?> So, if someone could help me I'd appreciate it so much. Regards!
  6. I want to convert an existing site to use prepared statements. This will be much easier if I can get the result of a SELECT query as an array to replace the array returned by mysqli_fetch_array. I am using PHP 5.4 with mysqlnd activated and should be able to use mysqli_stmt_get_result(stmt) to get such an array. But that function does not work and does not seem to be available at all. But all the documentation I'be read says it should be available in PHP 5.4. $query = "SELECT col1 FROM contactinfo WHERE col2 = ? && col3 = ? && (col4 = ? || col5 = ?) "; $stmt = mysqli_prepare($connect, $query); mysqli_stmt_bind_param($stmt, "ssss", $var1, $var2, $var3, $var4); mysqli_stmt_execute($stmt); $row = mysqli_stmt_get_result(stmt); $newvar = $row[0]; The actual query is much longer but this is the form. If I can't use mysqli_stmt_get_result, I'll probably abandon the transition. Can someone offer advice on my next move?
  7. Hi, I'm currently experiencing difficulties updating the database. I'm currently creating a 'Forgotten Password' feature. I've finished most of it, however when I attempt to update the database with a new password, nothing happens and the old password remains in the database. I've followed W3Schools example but I'm stuck. --------- The new password is generated by numbers 4 in total, ie $new_pass = (rand(1000,9999); and from the form I've used $user_email= $_POST["retrieve_email"]; then I use the line sql = "UPDATE registration SET Password=$new_pass WHERE Email=$user_email"; I can't get it to work, and I don't know why. Could anyone please write the code I need to make it work, or let me know how to proceed? Thank You. ps. I thought about deleting the entry and re-inserting it. Would that work (out of interest)?
  8. retrieving table names from database

    I made a set up for showing tables with a php script. Its based on a script from w3schools. // make connection with localhost $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // script calling to connect with dbase function write_content () { // reading the tables from the dbase $sql = "SHOW TABLES"; // show tables $result = $conn->query($sql); while ($row = $result->fetch_assoc()) { echo current($row) . '<br/>'; } $conn->close(); return; } echo "<br><br><br>"; echo "The following tables are found in the database " ; echo write_content (); The problem is that conn is a not defined variable.though it worked in a condition with if. Then a second error message is given sounding: Fatal error: Call to a member function query() on a non-object in ..... these errors concern this line: $result = $conn->query($sql);
  9. can not INSERT INTO getting a error.

    Hello, i am having issues adding info to a database i have a html from where a user should fill in charname and select ###### then press submit. if i do this i get the error ERROR:could not able to execute INSERT INTO character(charname, ######, xp, gold, accdate) VALUES(jay, male, 0, 100000, now()).You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character(charname, ######, xp, gold, accdate) VALUES(jay, male, 0, 100000, now())' at line 1 <?php include_once 'db_connect.php'; include_once 'psl-config.php'; $error_msg = ""; $now = time(); // check connection if($mysqli === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Escape user inputs for security $charname = mysqli_real_escape_string($mysqli, $_POST['charname']); $###### = mysqli_real_escape_string($mysqli, $_POST['######']); //attempt inser quesry execution $sql = "INSERT INTO character (charname, ######, gold, xp, accdate) VALUES ($charname, $######, 100000, 0, now())"; if(mysqli_query($mysqli, $sql)){ echo "Records added successfully."; } else{ echo " ERROR:could not able to execute $sql." .mysqli_error($mysqli); } // close connection mysqli_close($mysqli); ?> Table CREATE TABLE IF NOT EXISTS `character` ( `id` int(11) NOT NULL AUTO_INCREMENT, `charname` varchar(30) NOT NULL, `######` tinyint(4) NOT NULL, `gold` int(11) NOT NULL, `xp` int(11) NOT NULL, `accdate` timestamp NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; I was wondering if some one could explain me what i do wrong, and or have some tips how to make this better. the idea is to add a check to see in the "charname" is already used. and some other stuff. but first i like to see the info end up in my DB Thanks
  10. Hope you can help. I'm trying to install vtiger 6.2.0 on windows 8.1 - during the installation wizard there is the part with the required values testing. In this part everything is set to "yes" except mysqli support that appear as "no" under the present value. In the PHP.ini in C:Program Files (x86)vtigerCRM620php under Dynamic Extensions the line extension=php_mysqli.dll is without ; before it. in the PHP.ini in C:Program Files (x86)vtigerCRM620apachehtdocsvtigerCRMpkgphp under Dynamic Extensions there is no extension=php_mysqli.dll so I added it to the end of the column. Still the mysqli support appears as "no" under the present value. By the way - I don't have a section marked [php_MYSQLI] in my PHP.ini files - the only place that have something to do with php_mysqli.dll is in the ;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; section. ;;;;;;;;;;;;;;;;;;;;;; what should I do? By the way (2) - the Required Value of PHP Version is 5.5.0 and the Present Value is 5.3.10 (this is the php that comes with the vtiger installation EXE file). I wonder if 5.5.0 is the required value of PHP - why the exe install 5.3.10? Thanks for your help! Ram
  11. PHP > MySQLi > Is it depreciated?

    Hello all. I have come here to the source of web standards to understand PHP and the API's it uses to access databases. From my reading (why yes, I do know how to use google ) it seems both MySQLi and PDO are acceptable methods. Other than the boatload of "experts" on various forums and blogs shouting that MySQLi is depreciated, is there any real indication that it is? Now I don't want to start a MySQLi Vs PDO thread. I just want to know if MySQLi is still an acceptable API to use
  12. how do i convert this to PDO....HELP

    hello everyone..how do i code PDO for this script...please help me <?php if (isset($_POST['Login'])){ $UserName=$_POST['UserName']; $Password=$_POST['Password']; $hostname = 'localhost'; $username = 'root'; $password = ''; $database_name = 'ovs'; $mysqli = new mysqli($hostname, $username,$password, $database_name); $login_query=mysqli_query($mysqli,"select * from voters where Username='$UserName' and Password='$Password' and Status='Unvoted' and Year='1st year'") or die(mysqli_error()); $login_query1=mysqli_query($mysqli,"select * from voters where Username='$UserName' and Password='$Password' and Status='Voted'"); $count=mysqli_num_rows($login_query); $count1=mysqli_num_rows($login_query1); $row=mysqli_fetch_assoc($login_query); $id=$row['VoterID']; ?>index.php
  13. Php - Mysqli : Transactions

    I have many select insert update query , i have written transaction query but want to know if its safe or some need to be corrected. Also if all is ok i should get successful "Transaction completed successfully!" , but if something get wrong then error message showed be seen and ROLLBACK should be done , but its NOT .... not rollback is done Below is what I have tried. Please let me know if something is wrong: function autocommitfalse(){global $db;return mysqli_autocommit($db, FALSE);}function autocommittrue(){global $db;return mysqli_autocommit($db, TRUE);}function commitquery(){global $db;return mysqli_commit($db);}function rollbackedquery(){global $db;return mysqli_rollback($db);} =============================================================================== try {global $db;autocommitfalse();-----------------$SQLSELECT = "SELECT * FROM BC ";$result_as = mysqli_query($db,$SQLSELECT);$rsfetch = mysql_fetch_array($result_as);if(!$result_as ){throw new Exception('Wrong SQL SELECT: ' . $SQLSELECT. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$sqla ="INSERT INTO A (sd) VALUES ('df') where id=".$rsfetch['dh'];$result_a = mysqli_query($db,$sqla);if(!$result_a){throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$sqlb ="INSERT INTO B (sdds) VALUES ('trtrt') where id=".$rsfetch['dh'];$result_b =mysqli_query($db,$sqlb);if(!$result_{throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------$a = mysqli_insert_id($db);-----------------$sqlCb ="UPDATE CB SET A ='NM' where id=".$a ;$result_Cb = mysqli_query($db,$sqlCb);if($result_Cb === false || mysqli_affected_rows($db) == 0 ){throw new Exception('Wrong SQL SELECT: ' . $result_a. ' Error: '.db_error_msg($db) . db_error_no());}-----------------commitquery();echo 'Transaction completed successfully!';} catch (Exception $e) {echo"<br >";echo "<table align=center><tr><td>";echo $e->getMessage();echo "</td></tr></table>";echo"<br >";echo display_error(_("Transaction failed: transaction rolled back"));rollbackedquery();}autocommittrue(); Please let me know its correct or not , if need to correct then what , as still not rollbacked with above code..
  14. error

    this script keep returning warning mysqli_num_rows expect paramter 1 to be a result boolean given. Why? <html> <body> <h1>search engine</h1> <form action="search.php" method="get"> <input type="text" name="k" size='50' /> <input type="submit" name="submit" value='Search' /> </form> <hr /> <?php include "connect.php"; $k = $_GET['k']; $terms = explode(".", $k); $query = "SELECT * FROM users WHERE "; foreach($terms as $each) { $i++; if($i == 1) { $query .= "keywords LIKE '%$each%' "; } else { $query .= "OR keywords LIKE '%$each%' "; } } $query = mysqli_query($con, $query); $numrows = mysqli_num_rows($query); if($numrows > 0) { while($row = mysqli_fetch_array($query)) { $id = $row['id']; $title = $row['title']; $description = $row['description']; $keywords = $row['keywords']; $link = $row['link']; if($k == "") { echo ""; } else { echo "<h2><a href='$link'>$title</a></h2> $description"; } } } else { echo "no result on $k"; } ?> </body> </html>
  15. I have created some custom functions like these: function folder_exists($folder){ global $connection; $sql_folder_exists = "SELECT COUNT(`album_id`) FROM `albums` WHERE `folder` = '{$folder}' LIMIT 1"; $folder_exists = mysql_query($sql_folder_exists, $connection) or die(mysql_error()); return (mysql_result($folder_exists, 0) == 1) ? true : false;} function total_users(){global $connection;$sql_total_users = "SELECT COUNT(`user_id`) FROM `users` ";$total_users = mysql_query($sql_total_users,$connection) or die(mysql_error());return mysql_result($total_users, 0);} , but I decided to use the mysqli_* functions instead. My question is which mysqli_ function is used instead if the mysql_result in these cases??? I've searched through the manual and gives these functions mysqli_data_seek() , mysqli_field_seek() and mysqli_fetch_field(), but when i tried them they did not gave me the expected result and obviously ther's no mysqli_result() function.
  16. MySQLi PHP extension

    PHP's manual states that the MySQL extension is deprecated, you can see it on any of the mysql function references as in the following page:http://es.php.net/manual/en/function.mysql-connect.php I think it would be good if W3Schools changed or appended new information to their PHP tutorial about the MySQLi extension since it seems to be the most commonly used alternative. Maybe the object-oriented style might not be good to teach, as object-oriented programming would need to be explained in the tutorials, but MySQLi does have a procedural style as well.
×