Converting mysql to mysqli functions and getting parameter error - php

I'm new to mysqli and am upgrading all my code to use it.
I understand functions now need to have the $conn variable included with them.
Here is my code:
$query = "SELECT * FROM...";
$result = mysqli_query ($conn, $query);
while ($row = mysqli_fetch_array($conn, $result)) {
}
I'm getting the error:
PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
and I can't figure out what I'm missing.

and I can't figure out what I'm missing.
Missing? Nothing. Extra? :)
mysqli_fetch_array will take $result, which already knows about $conn; so mysqli_fetch_array($result) is correct, and adding $conn confuses it.

Related

php error Uncaught Error: Call to undefined function mysqli_fetch_all() [duplicate]

Thanks to the answers I have figured out that I am unable to use fetch_all() because i am using PHP 5.2.17 - fetch_assoc with while loop worked.
The function I am using fetch_all is coming back with this error:
Fatal error: Call to undefined method mysqli_result::fetch_all() in
$mysqli = new mysqli($host, $username, $password, $database);
$query = "LONG QUERY that works, tested in phpmyadmin"
$result = $mysqli->query($query);
$result->fetch_all(); or $mysqli->fetch_all() tried both
mysqli_fetch_all() was already tried.
$mysqli->close();
I am able to connect to the DB and I have pulled single rows. When I place the query in PHPMYADMIN I get 5 rows back.
Does this function even work? Is there a way I can place my data into an assoc array on my own?
This function is available since PHP 5.3.0. Possibly your version is older. Use fetch_assoc() instead.
while ($row = $result->fetch_assoc()) {
// do what you need.
}
mysqli::fetch_all() needs mysqlnd driver to be installed before you can use it.
The typical way to construct an associative array is in a while loop:
$results_array = array();
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$results_array[] = $row;
}
Issue seems to be 'mysqli' and 'mysqlnd' are not working together. I had the same issue in cpanel
Steps:
1) Go to CPanel dashboard
2) Go to 'Select PHP Version', you should see a bunch of checkboxes
3) Set PHP version (5.4 or above)
4) Uncheck the 'mysqli' extension and check both 'mysqlind' and 'nd_mysqli'
Apparently 'nd_mysqli' is 'mysqli' but configured to work with 'mysqlind' and to make it work you have to uncheck 'mysqli' due to settings conflicts.
Following answer I found here helped me.
Please be careful about using fetch_all():
http://www.php.net/manual/en/mysqli-result.fetch-all.php#88031
Read the note about mysqldn requirement.
As an addition to Fabrizios answer, please consider building up your array with a loop:
$array = array();
while($row = $result->fetch_assoc())
$array[] = $row;
If you don't want to iterate using Karolis' answer,
use
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$rows[] = $row;
}
to achieve the same result as
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
You may change constant to MYSQLI_NUM or MYSQLI_BOTH.
This optional parameter are constants indicating what type of array should be produced from the current row data.
Notice that mysqli_fetch_array($result,MYSQLI_ASSOC ) behaves identically to the mysqli_fetch_assoc() function, while mysqli_fetch_array($result,MYSQLI_NUM) will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
http://php.net/manual/en/mysqli-result.fetch-array.php
I had 5.6 but didn't work for me anyway. By enabling the mysqlnd driver it worked for me. Just write apt-get install php5-mysqlnd then restart php and you're good to go!
PHP Fatal error: Call to undefined function mysqli_fetch_all()
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);//not work
change to:php 5.3 or
$query = "SELECT * FROM `user_counter` ORDER BY id DESC LIMIT 20";
$result = mysqli_query($connection, $query) or die
("Error in Selecting " . mysqli_error($connection));
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
Just to add an additional note about the mysqlnd driver: It also has to have the mysqli API extension installed. Without the extension, fetch_all() still won't be available. I found this while troubleshooting why my code worked on one server but not another, both PHP > 5.3. Use phpinfo() to verify the installed extensions.
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
$resultset = array(); //you need to define array
while($row=$result->fetch_assoc()) {
$resultset[] = $row; //then insert result into the array
}
if(!empty($resultset))
{
return $resultset;}
else{return 'empty';};
}

How do I fix mysqli_store_result() expects parameter 1 to be mysqli, object given

I have looked at the manual for the function and cannot figure out what parameter would satisfy. I know several other questions have this problem but none of those solutions have helped.
Here is my code:
$id = $_GET['id'];
$_SESSION['id'] = $id;
$link = mysqli_connect("localhost", "root", "", "first_db");
mysqli_select_db($link, "first_db");
$query = mysqli_query($link, "Select * from list WHERE id ='$id'");
$count = mysqli_stmt_num_rows($query);
Since you are calling mysqli_query you don't actually need to call mysqli_store_result as that is part of what that does (see the manual). Also since you're not actually using a prepared statement you need to change the num_rows routine you are calling; replace
$count = mysqli_stmt_num_rows($query);
with
$count = mysqli_num_rows($query);

I get error when I load my login page becuase of my sql query function [duplicate]

This question already has answers here:
php mysqli query expects parameter 1 be to string
(2 answers)
Closed 6 years ago.
I am getting this error:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs
My code:
function dbQuery($sql)
{
$result = mysqli_query($sql) or die(mysqli_connect_error());
return $result;
}
It's inside a function, MySQLi is not having access to your connection as far as I know.
If your database connection is named $conn, you can write it like:
function dbQuery($sql) {
global $conn;
$result = mysqli_query($conn, $sql) or die(mysqli_connect_error());
return $result;
}
Please read the manual on how to use mysqli_query: http://php.net/manual/en/mysqli.query.php. The correct way to use it is:
$result = mysqli_query($conn,$sql);
where $conn is your mysqli connection, and $sql is the query to run.

sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in

im trying print records from my db (IIS, MSSQL PHP) but i have this error...
Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in
<?php
$serverName ="name\SQLEXPRESS";
$usr="sa";
$pwd="pasw";
$db="dbname";
$connectionInfo = array("UID" => $usr, "PWD" => $pwd, "Database" => $db);
$conn = sqlsrv_connect($serverName, $connectionInfo);
$sql = "SELECT first_col, s_col, t_col, FROM names ";
$res = sqlsrv_query($conn,$sql);
while ($row = sqlsrv_fetch_array($res)) {
print(
$row['first_col'].",".$row['s_col'].",".$row['t_col'].");
}
sqlsrv_close( $conn);
?>
Your query failed. This causes sqlsrv_query() to return false.
Your error in your query is an errant comma:
$sql = "SELECT first_col, s_col, t_col, FROM names ";
^^^^
HERE
Remove it and your query should work.
FYI, you don't check for errors in your code. You should always check to see if something failed, and if so, get the error message. You would have caught this quickly if you did.
The accepted answer is too localized and of no help for most users coming from Google, who need rather a generic answer, what to do when one gets such error in general.
This error message doesn't have any particular meaning, it's just a symptom telling us that the query execution failed. While we need to get the actual error message from SQL server. Hence every query should be executed in PHP like this:
$sql = "SELECT first_col, s_col, t_col, FROM names";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR);
}
What is going on here?
first, we are checking the query result, if case it's equal to false, which means the query failed
if so, we are calling sqlsrv_errors() which returns an array with all errors returned by SQL server
then we are converting this array to string using print_r()
and finally, throwing a conventional PHP error that could be handled the same way as any other error
In the end, a failed query will throw a PHP error that explains the reason, so one can read the SQL server error message and then fix it right away or Google this message to get the explanation/practical suggestions for their particular error
If you use Stored Procedure with SQL SERVE, you must use EXEC, in your code you used CALL
$check = sqlsrv_query($conn, "{CALL Mem_Users_Accede (?,?,?,?)}", $data);

Using the same mysqli connection ($conn=mysqli_connect) multiple times gives errors

I am using the mysqli functions (mysqli_connect, mysqli_select_db, mysqli_query) to call 1 select query and 2 stored procedures.
It seems that when I am using the same $connection (returned by mysqli_connect) multiple times, I am getting the following error message: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..."
Below is my code:
<?php
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$connection=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection, "$db") or die('Unable to select database.');
//First SELECT using $connection
$query=mysqli_query($connection, "SELECT item_name FROM items ORDER BY item_name DESC");
While ($result=mysqli_fetch_array($query,MYSQL_NUM))
{
$complete_result[] = $result[0];
$total_rows = $total_rows + 1;
}
//CALL to first sp using $connection
$query2 = mysqli_query($connection, "CALL sp_check_edits_remaining()");
while ($row2 = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$edits_remaining = $row2['edits_remaining'];
} // End while
//CALL to second sp using $connection
$query3 = mysqli_query($connection, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {);
$edits_id = $row3['id'];
} // End while
?>
Like I described, when I call the second sp, the above code gives me the error message mentioned above. (Please note that the connection is never closed.)
However, when I create another connection and provide it to the second sp call, this error disappears. This is shown in the code below
$connection2=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection2, "$db") or die('Unable to select database.');
//CALL to second sp using $connection
$query3 = mysqli_query($connection2, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {
$edits_id = $row3['id'];
} // End while
Can anyone please help me why this unexpected behavior?
Thanks and in advance!
It seems I have found a solution, which might be specific to my scenario.
My stored procs return only one row in the resultset.
So, after the CALL to the first sp and the corresponding while loop, I have simply added:
mysqli_next_result($connection);
This has removed the error message/warning I was receiving.
Anyone wants to comment whether this is the 'professional' approach?
You have an error somewhere, causing one of the mysql functions (probably the query call(s)) to return a boolean false, which you then blindly use in a fetch call. You need to add extra error handling, e.g.
$query = mysqli_query($connection, "...") or die(mysqli_error($connection));
never assume a query has succeeded.
enter code hereafter the query is finished, you must close the $connection then for another query, connect and assign the $connection again.
mysqli_close($connection);
$connection=mysqli_connect(bla,bla,bla,bla).

Categories