MySQLi failing to prepare a statement - php

I'm running two queries in my script room.php. Both are using MySQLi prepared statements, and their code are as follows:
/* Get room name */
$stmt = $mysqli->prepare('SELECT name FROM `rooms` WHERE r_id=?');
$stmt->bind_param('i', $roomID);
$stmt->execute();
$stmt->bind_result($roomName)
/* Add this user to the room */
$stmt = $mysqli->prepare('INSERT INTO `room_users` (r_id, u_id) VALUES (?, ?)');
$stmt->bind_param('ii', $roomID, $_SESSION['userID']);
$stmt->execute();
When I run the script, I get this error:
Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\room.php on line 24
Which is the second query. If I remove the first query from the script, everything runs fine. Likewise if I remove the second query. Which leads me to believe there's a problem because I'm reusing the $stmt object. If I try the second query using $stmt2 I still get the error.
All my database tables and fields exist, so there's nothing wrong with the queries.

All of the mysqli functions/methods can fail in which case they will return false. I.e. if prepare() fails $stmt isn't an object you can call a method on but a bool(false). You have to check the return values and add some error handling, e.g.
$stmt = $mysqli->prepare('SELECT name FROM `rooms` WHERE r_id=?');
if ( !$stmt ) {
printf('errno: %d, error: %s', $mysqli->errno, $mysqli->error);
die;
}
$b = $stmt->bind_param('i', $roomID);
if ( !$b ) {
printf('errno: %d, error: %s', $stmt->errno, $stmt->error);
}
$b = $stmt->execute();
if ( !$b ) {
and so on and on
see http://docs.php.net/mysqli-stmt.errno et al
in this case you probably bumped into the problem that you can't create an other statement while there are still results/result sets pending for the previous statement.
see http://docs.php.net/mysqli-stmt.close:
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Related

Can't execute second MYSQLI query in same PHP file

Here is my code
$stmt = $mysqli->prepare("SELECT * FROM `accountsToDo` WHERE `OKrname` = ?");
$stmt->bind_param("s", $OKCUsername);
/* execute prepared statement */
$stmt->execute();
if ($stmt->affected_rows > 0){
echo "Exists";
} else {
$stmt = $mysqli->prepare("INSERT INTO `accountsToDo`(`percentageOfMessages`, `RemoveDeletedAccounts`, `RemoveNoReply`, `RemoveNoResponse`, `minMatchPercent`, `minDistance`, `maxDistance`, `blacklistUsernames`, `userEmail`, `OKrname`, `OKword`) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("iiiiiiissss", $percentageOfMessages, $RemoveDeletedAccounts, $RemoveNoReply, $RemoveNoResponse, $minMatchPercent, $minDistance, $maxDistance, $blacklistUsernames, $userEmail, $OKrname, $OKword);
$stmt->execute();
}
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
But now I'm getting the error,
Call to a member function bind_param() on boolean in line 147.
Line 147 is
$stmt->bind_param("iiiiiiissss", $percentageOfMessages, $RemoveDeletedAccounts, $RemoveNoReply, $RemoveNoResponse, $minMatchPercent, $minDistance, $maxDistance, $blacklistUsernames, $userEmail, $OKrname, $OKword);
If all you are doing is inserting into a todo table if the master table doesn't have a matching row, you don't need two statements.
INSERT INTO `accountsToDo`
(`percentageOfMessages`, `RemoveDeletedAccounts`,
`RemoveNoReply`, `RemoveNoResponse`, `minMatchPercent`,
`minDistance`, `maxDistance`, `blacklistUsernames`,
`userEmail`, `OKrname`, `OKword`)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
WHERE NOT EXISTS (SELECT 1 FROM `accountsToDo` WHERE `OKrname` = ?);
Bind your params and you have save a call to the db. This has the advantage that "SELECT 1" acts as a cut operator so it is only evaluated until it finds the first TRUE.
You are missing a space between table name and a list of fields in your $mysqli->prepare
Try this:
$stmt = $mysqli->prepare("INSERT INTO `accountsToDo`
(`percentageOfMessages`,`RemoveDeletedAccounts`,
`RemoveNoReply`, `RemoveNoResponse`,
`minMatchPercent`, `minDistance`,
`maxDistance`, `blacklistUsernames`,
`userEmail`, `OKrname`, `OKword`)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
According to manual $mysqli->prepare will return FALSE if statement caused an error
UPDATE
Looks like your $mysqli->prepare is expecting 11 variables and you are trying to bind 12
The issue was that I didn't have
$stmt->store_result();
above the first $stmt->execute();

Call to undefined method mysqli_stmt::free()

I want to prepare a mysql script that first checks the id of the user based on given email and later on use this found id in the next query. What I did so far is as follows:
$find_id = "SELECT id from client
WHERE email = ? ";
$statement = $mysqli->prepare($find_id);
$statement->bind_param("s", $client_mail);
$statement->execute();
$statement->bind_result($id);
$statement->free();
$sql = "SELECT client_name, contact_name from client_addr
WHERE client_id = ? AND is_actual < ? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("is", $id, "Y");
$stmt->execute();
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);
but now I'm getting the error related to this line:
$statement->free();
that says Call to undefined method mysqli_stmt::free() in.
However, when I remove this line I'm getting the error:
Uncaught exception 'mysqli_sql_exception' with message 'Commands out of sync; you can't run this command now'
on this line:
$stmt = $mysqli->prepare($sql);
How can I fix it?
I believe the function you're trying to use would be mysqli_stmt::free_result(). You'll need to change this line:
$statement->free();
To:
$statement->free_result();
The second Uncaught exception occurs because mysqli is an unbuffered SQL query handler, so you should store your results if you're looping simultaneous executions with something like $stmt->store_result(); and then you can unload the mysqli buffer to state a new query.

Simple select query gives error

Does anyone have any idea why I get two errors for such a simple query? Error message are:
Warning: mysqli::prepare(): Couldn't fetch mysqli in (...)/functions.php on line 503
Fatal error: Call to a member function bind_param() on null in (...)functions.php on line 504
$query_select = ("SELECT * FROM vat WHERE vat_status = ?");
$stmt = $mysqli->prepare($query_select); // line 503
$stmt->bind_param("s", $vat_status);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows();
$stmt->bind_result ($vat_id ,
$vat_rate ,
$vat_account ,
$vat_description ,
$vat_status ,
$vat_timestamp );
The problem was that I was triggering an UPDATE statement and then an SELECT statement, and both of them used $stmt variable. That was what went wrong.
Now I use
mysqli_stmt_close($stmt);
Which really closes the $stmt and frees the result, so I can trigger after an update, the select statement.

Should I init MySQL every time I want to run a query in PHP?

I have a little (and stupid) problem: I'm building a PHP application using mysqli and a MySQL server. When the application is loaded, a variable called $database is initialized using
$database = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
This, of course, works perfectly. If I create an statement to do a query:
$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');
This still works. But, if I try to create another statement without closing the previous one, sometimes works, and sometimes now. The error I get when the creation of the statement fails is:
Fatal error: Call to a member function bind_param() on a non-object
And my question is: why? What should I do, open a connection (new mysql(...)) every time I want to create a new statement (and I have another open)?
Example
$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');
$stmt->bind_param('i', $aValue);
$stmt->execute();
/* do some other operations, without closing $stmt */
$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');
// Now, $stmt2 isn't initialized, so when the next line is run, the app fails
$stmt2->bind_param('ss', $someValue, $anotherValue);
If, before the
$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');
I add a simple
$stmt->close();
All works without any problems. So, what is the problem?
You cannot run another query until you have fetched all the results from the previous. Otherwise you will have to make a separate connection.
Did you remember to bind_param & execute ? :
$stmt->bind_param("s", $string);
$stmt->execute();
//etc..
OR
$stmt->bind_param("i", $int);
$stmt->execute();
//etc..
IF you want multiple queries : check out multi_query

PHP prepared statement within a prepared statement

I'm going through a video tutorial about doing a menu using a db. Instead of doing it with procedural PHP like in the video, I tried doing it with prepared statements OOP style. It doesn't work and I can't figure out why.
It runs fine until line 17, where it dies with this error:
Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\widget_corp\content.php on line 17
And here's the code:
<?php
$query = $connection->prepare('SELECT menu_name, id FROM subjects ORDER BY position ASC;');
$query->execute();
$query->bind_result($menu_name, $sid);
while ($query->fetch()){
echo "<li>{$menu_name} {$sid}</li>";
$query2 = $connection->prepare('SELECT menu_name FROM pages WHERE subject_id = ? ORDER BY position ASC;');
$query2->bind_param("i", $sid); //This is line 17
$query2->execute();
$query2->bind_result($menu_name);
echo "<ul class='pages'>";
while ($query2->fetch()){
echo "<li>{$menu_name}</li>";
}
echo "</ul>";
}
$query->close();
?>
Is it impossible to do a prepared statement within stmt->fetch();?
Figured it out:
After executing and binding the result, it has to be stored (if another prepared statement is to be put in the fetch). So the fetching in this case has to be read from a buffered result.
In other words, can't execute another query until a fetch on the same connection is in progress.
The working code:
$query = $connection->prepare("SELECT menu_name, id FROM subjects ORDER BY position ASC;");
$query->execute();
$query->bind_result($menu_name, $sid);
$query->store_result();
$stmt = mysqli_prepare($con,"SELECT menu_name, id FROM subjects ORDER BY position ASC");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $menu_name, $id);
while (mysqli_stmt_fetch($stmt))
{
$stmt2 = mysqli_prepare($con2,"SELECT menu_name FROM pages WHERE subject_id = ? ORDER BY position ASC;");
mysqli_stmt_bind_param($stmt2,$id);
mysqli_stmt_execute($stmt2);
mysqli_stmt_bind_result($stmt2, $name);
while (mysqli_stmt_fetch($stmt2))
echo $name;
}
look at the $con and $con2, you can not execute a prepare statement within another ps using the same connection !!!
Yes, you can have several prepared statements : one of the ideas of prepared statements is "prepare once, execute several times".
So, you should prepare the statement outside of the loop -- so it's prepared only once
And execute it, several times, insidde the loop.
The Fatal error you get means that $query2 on line 17, is not an object -- which means the prepare failed.
A prepare typically fails when there is an error in it ; are you sure your query is valid ? The tables and columns names are OK ?
You should be able to get an error message, when the prepare fails, using mysqli->error() -- or PDO::errorInfo()
You don't say what DB extension you are using but you don't seem to test the return value of any function you are using. You can't assume that DB calls will always run flawlessly.

Categories