Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() - php

I have following lines of code to fetch multiple records using PHP 7.3
$query = "Select * from tblorders";
$stmt = $connection->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
The last line issues as error.
Error Details
Uncaught Error: Call to undefined method mysqli_stmt::fetchAll()
I can confirm that the connection is not null and has proper connection details.
Am I missing anything?

This is because there is no such function! You are mixing PDO and mysqli.
If you want to fetch all records from a mysqli prepared statement you need to do it in two steps. First, fetch the result set using mysqli_stmt::get_result() and then use mysqli_result::fetch_all()
$query = "Select * from tblorders";
$stmt = $connection->prepare($query);
$stmt->execute();
$resultSet = $stmt->get_result();
$data = $resultSet->fetch_all(MYSQLI_ASSOC);
However, I would strongly advise learning PDO instead of mysqli as it is much easier and offers more options.

Related

MySQLI mysqli_store_result results with Malformed Packet error

I am in the process of converting some old MySQL code into MySQLI Prepared Statements and hit a snag:
If I run the same SQL code as prepared statement, I get a "Malformed Package" error. This happens even with extremely simple queries like "SELECT * FROM [TableName]".
I have the creation of the connection and setting of the Report level in a Seperate file altogether. So that code must be identicaly by definition.
As specific example, this code works:
$sql = "SELECT * FROM AngebotsDB";
$result = mysqli_query($link, $sql);
But this code:
$sql = "SELECT * FROM AngebotsDB";
// $result = mysqli_query($link, $sql);
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_execute($stmt);
$resultReference = mysqli_store_result($link); //throws exception
$result = mysqli_fetch_array($resultReference);
ends in:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message
'Malformed packet' in /home/cgroschupff/public_html/custom_code/DB
structure.php:16 Stack trace: #0 /home/cgroschupff/public_html/custom_code/DB structure.php(16):
mysqli_store_result(Object(mysqli)) #1 {main} thrown in
/home/cgroschupff/public_html/custom_code/DB structure.php on line 16
All I could really find is some old information of this happening when Connecting to the DB.
Note that the used MySQLi/PHP version is rather old (5.2.17?). So this could be a "long ago fixed" bug?
If you initialize a statement than you have to call other functions according to mysqli_stmt class so your code should be .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$resultReference = mysqli_stmt_store_result($link);
Now if you try var_dump($resultReference) than return true or false .
if you want to show result with mysqli_fetch_array so you have to pass mysqli_result parameter so for this you have to use mysqli_stmt_get_result .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt) ;
$output = mysqli_fetch_array($result) ;
Now you can see var_dump($output) than you have result .

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.

MySQLi prepared statements displaying error because of MySQLnd not installed

I am using this code to run a select statement in MySQLi
$stmt = $mysqli->prepare('SELECT * FROM admin WHERE forename = ? and surname = ? ');
$stmt->bind_param('vv', $forename, $surname);
$foremame = "Forename";
$surname = "Surname";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row["sequence"];
}
$stmt -> close();
$mysqli -> close();
But I am getting a fatal error saying:
Fatal error: Call to undefined method mysqli_stmt::get_result()
Because I do not have MySQLnd installed but I cannot install it as I am using a shared web server and the host will not install it.
How can I use a MySQLi prepared statement without having to have MySQLnd installed as I want to prevent SQL injection attacks
You can use $stmt->bind_result() to bind the results to variables, then $stmt->fetch() to fetch the results into the bound variables.
$stmt->execute();
$stmt->bind_result($var1, $var2, $var3, ...); // Use more meaningful variable names
while ($stmt->fetch()) {
echo $var3; // to get the third column in the results
}
I strongly recommend listing the colum names explicitly in the SELECT clause, rather than *, since this method of accessing the results is dependent on the specific order of the columns.

Is it possible to run a mysqli query directly via the link while a statement is opened?

I'm trying to do a simple operation on a MySQL database: my contacts have their complete names on a column called first_name while the column last_name is empty.
So I want to take what's on the first_name column and split it on the first occurrence of a white space and put the first part on the first_name column and the second part on the last_name column.
I use the following code but it's not working:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$statement = $connection->prepare("SELECT id, first_name FROM contacts");
$statement->execute();
$statement->bind_result($row->id, $row->firstName);
while ($statement->fetch()) {
$names = separateNames($row->firstName);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row->id);
}
$statement->free_result();
$statement->close();
$connection->close();
Can I use the $connection->query while having the statement open?
Best regards.
UPDATE
The $connection->query(...) returns FALSE and I get the following error:
PHP Fatal error: Uncaught exception 'Exception' with message 'MySQL Error - 2014 : Commands out of sync; you can't run this command now'
I changed the code to the following and worked:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row[0]);
}
$connection->close();
Can I use the $connection->query while having the statement open?
Yes. It will return a new result object or just a boolean depending on the SQL query, see http://php.net/mysqli_query - In your case of running an UPDATE query it will always return a boolean, FALSE if it failed, TRUE if it worked.
BTW, the Mysqli connection object is not the Mysqli statement object, so they normally do not interfere with each other (disconnecting might destroy/break some statements under circumstances, but I would consider this an edge-case for your question you can ignore for the moment).
I wonder why you ask actually. Maybe you should improve the way you do trouble-shooting?
I can only have one active statement at a given time, so I had to make one of the queries via the $connection->query() method.
As #hakre mentioned:
I still keep my suggestion that you should (must!) do prepared statements instead of query() to properly encode the update values
I opted to use the statement method for the update query, so the final working code is the following:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
$statement = $connection->prepare("UPDATE contacts SET first_name=?, last_name=? WHERE id=?");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$statement->bind_param('ssi', $names[0], $names[1], $row[0]);
throwExceptionOnMySQLStatementError($statement, "Could not bind parameters", $logger);
$statement->execute();
throwExceptionOnMySQLStatementError($statement, "Could not execute", $logger);
}
$statement->free_result();
$statement->close();
$connection->close();
Thanks to all that gave their inputs, specially to #hakre that helped me to reach this final solution.

PDO Database access WHERE title = $title

I'm trying to learn to use PDO instead of MySQLi for database access and I'm having trouble selecting data from the database. I want to use:
$STH = $DBH->query('SELECT * FROM ratings WHERE title=$title ORDER BY date ASC');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['title'];
}
but I'm getting this error:
Fatal error: Call to a member function setFetchMode() on a
non-object in
/home/owencont/public_html/owenstest.com/ratemystudents/index.php
on line 6
If I take out the WHERE statement it works fine. How can I select a row based on if it's value matches a variable?
Thanks,
Owen
It's likely a SQL syntax error, because you forgot to quote $title. It ended up as bareword in the query (also not even interpolated as string), resulting in an error. And your PDO connection was not configured to report errors. Use ->quote() on arguments before the ->query():
$title = $DBH->quote($title);
$STH = $DBH->query("SELECT * FROM ratings WHERE title=$title ");
Or better yet, use parameterized SQL:
$STH = $DBH->prepare("SELECT * FROM ratings WHERE title=? ");
$STH->execute(array($title));
Take a look at PDO::prepare and PDOStatement::execute. The safest way to add user content to a query is to prepare a basic statement and bind the parameter to it. Example (note the question mark in the SQL statement):
$STH = $DBH->query('SELECT * FROM ratings WHERE title=? ORDER BY date ASC');
$STH->execute( array( $title ) );
while( $row = $STH->fetch( PDO::FETCH_ASSOC ) );
Make PDO throw errors so you can see what exactly goes wrong. See How to squeeze error message out of PDO?
You are probably missing quotes around $title but this scenario really calls for prepared statements instead.
remove the variable out of the sql statement because its a php variable
$STH = $DBH->query('SELECT * FROM ratings WHERE title=' . $title . 'ORDER BY date ASC');
Use double quotes instead of single quotes as a parameter of the query-method.
The reason you're getting this error is because the query-method fails and so the $STH object isn't created. You should implement some error handling.

Categories