I have been using the traditional method of query db with out prepared statement. So decided to move to prepared statement now as below are my codes.
$link = new mysqli(dbHost, dbUser, dbPassword, dbDatabase);
if($link->connect_error) {
die('bind_param() failed: ' . htmlspecialchars($link->connect_error));
}
$stmt = $link->stmt_init();
$selectQuery1 ="Select * From tblUser Where tblUser.userName=? ";
$stmt1 = mysqli_prepare($link, $selectQuery1);
if ( false===$stmt1 ) {
die('stmt1 prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc1 = $stmt1->bind_param('s', $userName);
if ( false===$rc ) {
die('rc1 bind_param() failed: ' . htmlspecialchars($stmt1->error));
}
$execute1 = $stmt1->execute();
if ( false===$execute1 ) {
die('execute1 execute() failed: ' . htmlspecialchars($stmt1->error));
}
$store1=$stmt1->store_result();
if ( false===$store1 ) {
die('store1() failed: ' . htmlspecialchars($stmt1->error));
}
$count1=$stmt1->num_rows;
$result1 = $stmt1->get_result();
if ( false===$result1 ) {
die('result1 () failed: ' . htmlspecialchars($stmt1->error));
}
The query worked well till this line $count1=$stmt1->num_rows; and the moment I put this codes $result1 = $stmt1->get_result(); my page failed and I found out that I must now change to mysql native driver etc. My biggest worry is by changing the driver it might effect all my other existing application. So what is the best mechanism to mitigate is there any other method to retrieve the result or move to PDO ? I want to be able to use this mechanism mysql_fetch_array($result, MYSQL_ASSOC) to get my select results ?
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm trying to insert a variable into a mysql database. I've read the various posts about how to do this however these don't seem to work for me, the following code doesn't write anything to the database (the variable seems to break the query) however does if I don't use variables, can anyone tell me what I've doing wrong here?
$dbhost = 'zzzzzzzzz';
$dbuser = 'xxxxxxxxx';
$dbpass = 'yyyyyyyyy';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
// VARIABLE SETUP;
$variable = 'variable';
$variable = mysql_real_escape_string($variable);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", '$variable')';
mysql_select_db('wwwwww');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
First of all, for your issue you could try:
$sql = "INSERT INTO db_variables_insert".
"(time, variable) ".
"VALUES ( '2016-02-19 04:23:44', '".$variable."')";
However, you could rewrite this more sane as a prepared statement like:
/* mysqli_* to connect - ** See note on PDO below ** */
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
$sql = "INSERT INTO db_variables_insert (time, variable) VALUES (?,?)";
if ($stmt = $mysqli->prepare($sql)) {
/* Prepared statement, stage 2: bind parameters and execute */
$time = '2016-02-19 04:23:44';
// Assuming you already define $variable here
if ($stmt->bind_param("ss", $time, $variable)) {
/* Here this bit ^ can be "i" (integer), "s" (string) etc */
$execute = $stmt->execute();
if($execute === FALSE) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* ^ you are done executing the sql if no errors */
} else {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
} else {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* explicit close recommended */
$stmt->close();
Notes:
/** Recommended: Connect with PDO **/
$conn = new PDO('mysql:host=localhost;dbname=my_db;charset=UTF-8','user', 'pwd');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
^ useful to visit and practice:
PDO Tutorial for MySQL Developers
Prepared Statements
You need to use . to concatenate strings in PHP, you can't just put the variable next to the string. And if the variable column is a string, you need to put its value in quotes.
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", "' . $variable'")';
You can also write this as a single string with variable substitution, using double quotes around the PHP string.
$sql = "INSERT INTO db_variables_insert
(time, variable)
VALUES ( '2016-02-19 04:23:44', '$variable')";
I'm using a prepared statement that fails and I don't know why (no error is returned)Here's my code:
$stmt = $db->prepare("SELECT id, temps, nom, classes FROM profs WHERE matiere = ? AND pass = 0");
if ( false===$stmt ) {
die('prepare() failed: ('.$db->errno.')' . htmlspecialchars($db->error));
}
$rc = $stmt->bind_param("s", $mat);
if ( false===$rc ) {
die('bind_param() failed: ('.$db->errno.')' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: ('.$db->errno.')' . htmlspecialchars($stmt->error));
}
This returns only: "prepare() failed: (0)"
Where's the problem?
SELECT id, temps, nom, classes FROM profs WHERE matiere = ? AND pass = 0
Is this query valid? Does the profs table exist, and do the columns (id, temps, nom, classes, matiere, pass) exist (and spelt correctly!)
I'm new to mysqli, I wrote a function as below.
1 - I couldn't find a way for SELECT * query and having bind_result to assign each column value to the same name variable. (e.g. name column value of #row stores to $name)
I think bind_result() has no function on a SELECT * query?
2 - So I tried another option, to fetch all rows and assign them to appropriate variable manually through a loop. I think I should use $query->fetch_all() or $query->fetch_assoc() for looping but I encounter with this:
Fatal error: Call to undefined method mysqli_result::fetch_all()
or
Fatal error: Call to undefined method mysqli_result::fetch_assoc()
However I did a phpinfo() and saw mysqlnd was enabled and php version is 5.4.7 (running XAMPP v1.8.1)
And 3- what finally I did is below idea that doesn't work either.
function the_names($name)
{
global $db;
if($query = $db->prepare("SELECT * FROM users where name=?"))
{
$query->bind_param('s', $name);
if($query->execute())
{
$query->store_result();
if($query->num_rows > 1)
{
while($row = $query->fetch())
{
echo $row['name']; // Here is the problem
}
}
else
echo "not valid";
$query->close();
}
}
}
I need a way to store all fetched data as what bind_result() does, or having them in an array for later use, and it's much better to know both. tnx
One word to answer all your questions at once - PDO
It has everything you are trying to get from mysqli (in vain):
function the_names($name)
{
global $db;
$query = $db->prepare("SELECT * FROM users where name=?");
$query->execute(array($name));
return $query->fetchAll();
}
$names = the_names('Joe');
foreach ($names as $row) {
echo $row['name'];
}
Note the proper way of using a function. it should never echo anything, but only return the data for the future use
If your mysqli code doesn't have binding_param() you can just write code like below :
$mysqli = new mysqli("localhost" , "root" , "" , "database_name");
$result = $mysqli->query( "SELECT * FROM users where name=" . $name) ;
while ( $row = $result->fetch_assoc() ) {
echo $row["name"];
}
If you use binding_param() code , you also need to set bind_result()
$db = new mysqli("localhost" , "root" , "" , "database_name");
function the_names($name){
global $db;
/* Prepared statement, stage 1: prepare */
if (!($query = $db->prepare("SELECT * FROM users where name=?"))) { # prepare sql
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$query->bind_param("s", $name)) { # giving param to "?" in prepare sql
echo "Binding parameters failed: (" . $query->errno . ") " . $query->error;
}
if (!$query->execute()) {
echo "Execute failed: (" . $query->errno . ") " . $query->error;
}
$query->store_result(); # store result so we can count it below...
if( $query->num_rows > 0){ # if data more than 0 [ that also mean "if not empty" ]
# Declare the output field of database
$out_id = NULL;
$out_name = NULL;
$out_age = NULL;
if (!$query->bind_result($out_id, $out_name , $out_age)) {
/*
* Blind result should same with your database table !
* Example : my database
* -users
* id ( 11 int )
* name ( 255 string )
* age ( 11 int )
* then the blind_result() code is : bind_result($out_id, $out_name , $out_age)
*/
echo "Binding output parameters failed: (" . $query->errno . ") " . $query->error;
}
while ($query->fetch()) {
# print the out field
printf("id = %s <br /> name = %s <br /> age = %s <br />", $out_id, $out_name , $out_age);
}
}else{
echo "not valid";
}
}
the_names("panji asmara");
Reference :
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Here's the code:
<?php
$sql = mysql_query($db, "CALL selectproducts()");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysql_error());
} else {
while($row=mysql_fetch_array($sql))
{
$id=$row['prodname'];
$name=$row['proddescription'];
$desc=$row['prodsupplier'];
$supp=$row['proddate'];
$date=$row['prodprice'];
$qtyleft=$row['prodquantity'];
Getting this Error:
Warning: mysql_query() expects parameter 2 to be resource, string given in C:\xampp\htdocs\inventory\tableedit.php on line 166
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\inventory\tableedit.php on line 170
Why is it has errors when in fact i have no parameters in call procedure?
Should be:
mysql_query("CALL selectproducts()", $db);
Documentation
Note that the mysql_ functions are now depreciated.
Try this method:
<?php
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, $hostname, $username, $password, $dbName);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL simpleproc()";
if (mysqli_real_query($link,$query)) {
if ($result2 = mysqli_store_result($link)) {
while ($row = mysqli_fetch_assoc($result2)) {
$q = $row["login"];
echo $q;
}
}
}
mysqli_close($link);
?>
I do believe you're getting your mysql_query arguments getting mixed up, where was $db is the second parameter, and the first is the MySQL query to be executed.
Although furthermore, you're probably better off using mysqli instead for future proofing:
<?php
$mysqli = new mysqli('username', 'username', 'password', 'database' );
$result = $mysqli->query("CALL selectproducts()");
if( !$result ) {
die('Query failed returning error: '. $mysqli->connect_errno );
} else {
while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['prodname'];
$name = $row['proddescription'];
$desc = $row['prodsupplier'];
$supp = $row['proddate'];
$date = $row['prodprice'];
$qtyleft = $row['prodquantity'];
}
}
?>
From checking the mysqli PHP Docs for calling stored procedure:
<?php
/**
* Prepare Stored Procedure
**/
if (!($result = $mysqli->prepare("CALL selectproducts()"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$result->execute()) {
echo "Execute failed: (" . $result->errno . ") " . $result->error;
}
/**
* Iterate through each result
**/
do {
if ($res = $result->get_result()) {
printf("---\n");
var_dump(mysqli_fetch_all($res));
mysqli_free_result($res);
} else {
if ($result->errno) {
echo "Store failed: (" . $result->errno . ") " . $result->error;
}
}
} while ($result->more_results() && $result->next_result());
?>
EDIT (2011-07-23)
Have gotten some very helpful answers, both of which I've tried implementing. But I can't seem to get back the id from my Get_Security statement. I'm pretty sure my problem is that, in my first call statement Get_Security, the last three parameters are set to NULL. Seems like other people have the same problem. Doesn't seem like there's much documentation on having NULL as an input. How does one go about this?
NEW CODE
$stmt = mysqli_stmt_init($link);
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
}
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$stmt = mysqli_stmt_init($link);
$sql = "CALL Add_Active('$id','Research')";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
$stmt = mysqli_stmt_init($link);
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to INSERT INTO Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
ORIGINAL ENTRY
Searched extensively (e.g. PHP Manual, SO questions) but answers are confusing.
I need to execute 3 of SQL statements in a row:
Call stored procedure Get_Security that takes some inputs and returns an array, including the id.
Call another stored procedure Add_Active that takes the returned id from Get_Security as an input.
Insert some variables into my table.
Problem: I'm getting the MySQL Error Number 2014: "Commands out of sync; you can't run this command now".
I know I have to use mysqli_stmt_prepare, mysqli_stmt_execute, and mysqli_stmt_close to resolve this, but it's very confusing how to do this.
Would very much appreciate help in how to translate this using the above functions.
CODE:
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
I hope this helps. From what I can tell you aren't doing anything too fancy, so this should suffice. PDO does also support IN/OUT params to stored procedures as well, but I didn't see you using them.
Please note, PDO handles errors in different ways depending on how it is initialized. So I've skipped error handling here. Please let me know if you have questions.
Also note that until you add a DSN (MySQL's for example) this code doesn't care what database type it is, so the DSN can be a config value making your code more portable. I'm sure you could also see how this code could easily be expanded into a class/model structure (specifically the security check SP could become a PHP method)
$db = new PDO(); // http://www.php.net/manual/en/pdo.construct.php for params
// These generate PDO_Statement (see: http://www.php.net/manual/en/class.pdostatement.php)
$securityStmt = $db->prepare("CALL Get_Security( ?, ?, ?, ?, ? )");
$addActiveStmt = $db->prepare("CALL Add_Active( ?, ? )");
$insertStmt = $db->prepare("INSERT INTO MyTable SET id=?, open_items=?, attachments=?");
// Security CALL
$securityStmt->bindParam( 1, $symbol, PDO::PARAM_STR );
$securityStmt->bindParam( 2, $tagName, PDO::PARAM_STR );
$securityStmt->bindParam( 3, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 4, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 5, NULL, PDO::PARAM_NULL );
$securityStmt->execute();
// Bind the ID to a variable is useful sometimes...
$securityStmt->bindColumn( 'id', $securityId );
$securityStmt->fetch( PDO::FETCH_BOUND );
/*
Insert + Active call
These are much simpler because we don't need to set the data types of the input
(they are all string I hope...you didn't mention what the last 2 were in the insert).
*/
$addActiveStmt->execute(
array(
$securityId,
'Wedge Research'
)
);
$insertStmt->execute(
array(
$securityId,
$openItems,
$attachments
)
);
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "CALL SOMETHING()");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
mysqli_stmt_close($stmt);
So I've figured out how to solve this with my original code by simply closing the link to the database after every query. I would love to do prepared statements instead, but at least this works.
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "INSERT INTO myTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}