I am using mysqli to get the row but it is not giving me row, and there is no error in query.
$query="select * from members where useremail='$user_email' and password='$password'";
$result=$db->query($query);
$row = $db->fetch_array($result);
echo $row['id'];
My query Function
function query($query){
$result=mysqli_query($this->conn, $query);
if(!$result){
echo $this->err_msg = mysqli_error($this->conn);
return false;
}else{
return $result;
}
}
My fetch_array Function
function fetch_array($result){
return mysqli_fetch_array($result);
}
How can i get Row using mysqli ?
Change your original code to reflect bound parameters using mysqli, this is more secure and should work
$query="select * from members where useremail='$user_email' and password='$password'";
$result=$db->query($query);
$row = $db->fetch_array($result);
echo $row['id'];
to bound parameters using mysqli prepared statements
$query="select id from members where useremail=? and password=?"; // Don't use select *, select each column, ? are placeholders for your bind variables
$stmt = $connection->prepare($query);
if($stmt){
$stmt->bind_param("ss",$user_email,$password); // Bind in your variables, s is for string, i is for integers
$stmt->execute();
$stmt->bind_result($id); // bind the result to these variables, in the order you select
$stmt->store_result(); // Store if large result set, can throw error if server is setup to not handle more than x data
$stmt->fetch();
$stmt->close();
}
echo $id; // this would be same as $row['id'], $id now holds for example 5.
If you select multiple things, such as "SELECT id,name FROM...", then when you bind_result(..), just bind them n there. $stmt->bind_result($id,$name);
now $id and $name hold the column data for that row matching your query. If there would be multiple rows matching, instead of $stmt->fetch() you'd do
while($stmt->fetch()){ // just like while($row = $result->fetch_assoc()){}
echo $id;
echo $name
}
Related
I would like to see an example of how to call using bind_result vs. get_result and what would be the purpose of using one over the other.
Also the pro and cons of using each.
What is the limitation of using either and is there a difference.
Although both methods work with * queries, when bind_result() is used, the columns are usually listed explicitly in the query, so one can consult the list when assigning returned values in bind_result(), because the order of variables must strictly match the structure of the returned row.
Example 1 for $query1 using bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query1);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($id, $first_name, $last_name, $username);
while ($stmt->fetch()) {
echo 'ID: '.$id.'<br>';
echo 'First Name: '.$first_name.'<br>';
echo 'Last Name: '.$last_name.'<br>';
echo 'Username: '.$username.'<br><br>';
}
Example 2 for $query2 using get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query2);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
/* Get the number of rows */
$num_of_rows = $result->num_rows;
while ($row = $result->fetch_assoc()) {
echo 'ID: '.$row['id'].'<br>';
echo 'First Name: '.$row['first_name'].'<br>';
echo 'Last Name: '.$row['last_name'].'<br>';
echo 'Username: '.$row['username'].'<br><br>';
}
bind_result()
Pros:
Works with outdated PHP versions
Returns separate variables
Cons:
All variables have to be listed manually
Requires more code to return the row as array
The code must be updated every time when the table structure is changed
get_result()
Pros:
Returns associative/enumerated array or object, automatically filled with data from the returned row
Allows fetch_all() method to return all returned rows at once
Cons:
requires MySQL native driver (mysqlnd)
Examples you can find on the respective manual pages, get_result() and bind_result().
While pros and cons are quite simple:
get_result() is the only sane way to handle results
yet it could be not always available on some outdated and unsupported PHP version
In a modern web application the data is never displayed right off the query. The data has to be collected first and only then output has to be started. Or even if you don't follow the best practices, there are cases when the data has to be returned, not printed right away.
Keeping that in mind let's see how to write a code that returns the selected data as a nested array of associative arrays using both methods.
bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query1);
$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $first_name, $last_name, $username);
$rows = [];
while ($stmt->fetch()) {
$rows[] = [
'id' => $id,
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
];
}
and remember to edit this code every time a column is added or removed from the table.
get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query2);
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
and this code remains the same when the table structure is changed.
And there's more.
In case you decide to automate the boring routine of preparing/binding/executing into a neat function that would be called like this
$query = 'SELECT * FROM `table` WHERE id = ?';
$rows = prepared_select($query, [$id])->fetch_all(MYSQLI_ASSOC);
with get_result() it will be quite a plausible task, a matter of just a few lines. But with bind_param() it will will be a tedious quest.
That's why I call the bind_result() method "ugly".
get_result() is only available in PHP by installing the MySQL native driver (mysqlnd). In some environments, it may not be possible or desirable to install mysqlnd.
Notwithstanding, you can still use mysqli to do SELECT * queries, and get the results with the field names - although it is slightly more complicated than using get_result(), and involves using PHP's call_user_func_array() function. See example at How to use bind_result() instead of get_result() in php which does a simple SELECT * query and outputs the results (with the column names) to an HTML table.
Main difference I've noticed is that bind_result() gives you error 2014, when you try to code nested $stmt inside other $stmt, that is being fetched (without mysqli::store_result() ):
Prepare failed: (2014) Commands out of sync; you can't run this command now
Example:
Function used in main code.
function GetUserName($id)
{
global $conn;
$sql = "SELECT name FROM users WHERE id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()) {
return $name;
}
$stmt->close();
} else {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
}
Main code.
$sql = "SELECT from_id, to_id, content
FROM `direct_message`
WHERE `to_id` = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('i', $myID);
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($from, $to, $text);
/* fetch values */
while ($stmt->fetch()) {
echo "<li>";
echo "<p>Message from: ".GetUserName($from)."</p>";
echo "<p>Message content: ".$text."</p>";
echo "</li>";
}
/* close statement */
$stmt->close();
} else {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
I'm currently going thorough a site and replacing all the functions which used to return mysql_fectch_array() results, which are put into while loops elsewhere. I'm trying to make them return the same data in the same format but by using mysqli prepared statements output. I have been successful with the code below in producing the same formatted output for single row results.
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
But how can I get this code to work when it returns more than one row? I want it to be produce the same result as if I had written:
return mysql_fetch_array($result);
Is it possible?
Consider the following adjustment, passing query results into an associative array:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
You will notice I explicitly select the query's fields to avoid an indeterminate loop through query results.
Ok I have managed to get it to work without using get_result()
This is how I did it with alot of help from Parfait and Example of how to use bind_result vs get_result
function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
Its not exactly the same output as using a mysql_fetch_array() so where it is used I have to change the loop to:
foreach($saved_rules AS $row){}
from
while ($row = mysql_fetch_array($saved_rules){}
I would like to see an example of how to call using bind_result vs. get_result and what would be the purpose of using one over the other.
Also the pro and cons of using each.
What is the limitation of using either and is there a difference.
Although both methods work with * queries, when bind_result() is used, the columns are usually listed explicitly in the query, so one can consult the list when assigning returned values in bind_result(), because the order of variables must strictly match the structure of the returned row.
Example 1 for $query1 using bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query1);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($id, $first_name, $last_name, $username);
while ($stmt->fetch()) {
echo 'ID: '.$id.'<br>';
echo 'First Name: '.$first_name.'<br>';
echo 'Last Name: '.$last_name.'<br>';
echo 'Username: '.$username.'<br><br>';
}
Example 2 for $query2 using get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query2);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
/* Get the number of rows */
$num_of_rows = $result->num_rows;
while ($row = $result->fetch_assoc()) {
echo 'ID: '.$row['id'].'<br>';
echo 'First Name: '.$row['first_name'].'<br>';
echo 'Last Name: '.$row['last_name'].'<br>';
echo 'Username: '.$row['username'].'<br><br>';
}
bind_result()
Pros:
Works with outdated PHP versions
Returns separate variables
Cons:
All variables have to be listed manually
Requires more code to return the row as array
The code must be updated every time when the table structure is changed
get_result()
Pros:
Returns associative/enumerated array or object, automatically filled with data from the returned row
Allows fetch_all() method to return all returned rows at once
Cons:
requires MySQL native driver (mysqlnd)
Examples you can find on the respective manual pages, get_result() and bind_result().
While pros and cons are quite simple:
get_result() is the only sane way to handle results
yet it could be not always available on some outdated and unsupported PHP version
In a modern web application the data is never displayed right off the query. The data has to be collected first and only then output has to be started. Or even if you don't follow the best practices, there are cases when the data has to be returned, not printed right away.
Keeping that in mind let's see how to write a code that returns the selected data as a nested array of associative arrays using both methods.
bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query1);
$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $first_name, $last_name, $username);
$rows = [];
while ($stmt->fetch()) {
$rows[] = [
'id' => $id,
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
];
}
and remember to edit this code every time a column is added or removed from the table.
get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query2);
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
and this code remains the same when the table structure is changed.
And there's more.
In case you decide to automate the boring routine of preparing/binding/executing into a neat function that would be called like this
$query = 'SELECT * FROM `table` WHERE id = ?';
$rows = prepared_select($query, [$id])->fetch_all(MYSQLI_ASSOC);
with get_result() it will be quite a plausible task, a matter of just a few lines. But with bind_param() it will will be a tedious quest.
That's why I call the bind_result() method "ugly".
get_result() is only available in PHP by installing the MySQL native driver (mysqlnd). In some environments, it may not be possible or desirable to install mysqlnd.
Notwithstanding, you can still use mysqli to do SELECT * queries, and get the results with the field names - although it is slightly more complicated than using get_result(), and involves using PHP's call_user_func_array() function. See example at How to use bind_result() instead of get_result() in php which does a simple SELECT * query and outputs the results (with the column names) to an HTML table.
Main difference I've noticed is that bind_result() gives you error 2014, when you try to code nested $stmt inside other $stmt, that is being fetched (without mysqli::store_result() ):
Prepare failed: (2014) Commands out of sync; you can't run this command now
Example:
Function used in main code.
function GetUserName($id)
{
global $conn;
$sql = "SELECT name FROM users WHERE id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()) {
return $name;
}
$stmt->close();
} else {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
}
Main code.
$sql = "SELECT from_id, to_id, content
FROM `direct_message`
WHERE `to_id` = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('i', $myID);
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($from, $to, $text);
/* fetch values */
while ($stmt->fetch()) {
echo "<li>";
echo "<p>Message from: ".GetUserName($from)."</p>";
echo "<p>Message content: ".$text."</p>";
echo "</li>";
}
/* close statement */
$stmt->close();
} else {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
Trying to transition over my old mysql queries to mysqli prepared statements. I've got everything figured out except for one thing. How can I get the query results stored as an array? I used to do this like this:
$sql = "SELECT * FROM Users";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result) {
// do stuff
}
Now I have the following code. In this case, my array is a single record, so I don't need to iterate over it, but I want to hold it as an array so that I can refer to its field names. Also, I will have other queries that will return multiple records, so I'll need to iterat then.
$sql = "SELECT * FROM Users
WHERE (LOWER(first_name)=LOWER(?) && LOWER(last_name)=LOWER(?))";
$stmt = mysqli_stmt_init($link);
$this_user;
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, store results in an array */
mysqli_stmt_execute($stmt);
$result = mysqli_fetch_array($stmt);
if (mysqli_num_rows($result) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
$tag_result = "failure";
$tag_message = "No matching user found";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
if (mysqli_num_rows($result) > 1) {
mysqli_close($link);
$tag_result = "failure";
$tag_message = "Multiple records found for this user.";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
$this_user = mysqli_fetch_array($result);
/* close statement */
mysqli_stmt_close($stmt);
}
$id = $this_user['id'];
$first_name = $this_user['first_name'];
$last_name = $this_user['last_name'];
// and so on...
Can somebody tell me what I am doing wrong? Thanks!
EDIT: With big thanks to Phil, I've modified my code. However, I still seem to be returning 0 rows even though my input parameters should return exactly 1 row. Here is what I have:
$sql = "SELECT id, first_name, last_name, group_id, email, cell
FROM Users
WHERE (first_name=? && last_name=?)";
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, bind result, and fetch value */
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $first_name, $last_name, $group_id, $email, $cell);
mysqli_stmt_fetch($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
echo "No results returned";
die();
}
...
}
This always outputs No results returned when it should find 1 row and skip right past that block. I've been staring at this for a long time, but I just can't see what I am doing wrong.
Your script contains numerous errors (as mentioned in comments above). Here's a simple step-by-step...
Prepare a statement and bind parameters
$stmt = $link->prepare($sql);
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
// you can error check this too but it rarely goes wrong
$stmt->bind_param('ss', $first_name, $last_name);
Execute the statement and store the result
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->store_result();
Do your number of row checks against $stmt->num_rows...
if ($stmt->num_rows == 0) {
// ...
}
if ($stmt->num_rows > 1) {
// ...
}
Bind and fetch the result
// This relies on the SELECT column ordering.
// You should probably change your SELECT statement to
// SELECT id, first_name, last_name FROM Users...
$stmt->bind_result($id, $first_name, $last_name);
$stmt->fetch();
$stmt->close();
$link->close();
If you want to fetch the single result row as an associative array, try this instead
$result = $stmt->get_result(); // note - this requires the mysqlnd driver
$this_user = $result->fetch_array(MYSQLI_ASSOC);
$result->free();
$stmt->close();
$link->close();
I am receiving a fatal error in my php/mysqli code which states that on line 46:
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in ...
I just want to know how can I remove this fatal error?
The line of code it is pointing at is here:
$row = $stmt->fetch_assoc();
ORIGINAL CODE:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
UPDATED CODE:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1){
$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];
}
The variable $stmt is of type mysqli_stmt, not mysqli_result. The mysqli_stmt class doesn't have a method "fetch_assoc()" defined for it.
You can get a mysqli_result object from your mysqli_stmt object by calling its get_result() method. For this you need the mysqlInd driver installed!
$result = $stmt->get_result();
row = $result->fetch_assoc();
If you don't have the driver installed you can fetch your results like this:
$stmt->bind_result($dbUser, $dbEmail);
while ($stmt->fetch()) {
printf("%s %s\n", $dbUser, $dbEmail);
}
So your code should become:
$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute();
// bind variables to result
$stmt->bind_result($dbUser, $dbEmail);
//fetch the first result row, this pumps the result values in the bound variables
if($stmt->fetch()){
echo 'result is ' . dbEmail;
}
Change,
$stmt->store_result();
to
$result = $stmt->store_result();
And
Change,
$row = $stmt->fetch_assoc();
to
$row = $result->fetch_assoc();
You have missed this step
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result(); // you have missed this step
$row = $res->fetch_assoc();
I realized that this code was provided as an answer somewhere on stackoverflow:
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
I tried it to get the number of rows but realized that i didnt need the line $stmt->store_result();, and it didn't get me my number. I used this:
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
......
$row = $result->fetch_assoc();
$sample = $row['sample'];
It's best to use mysqlnd as Asciiom pointed out. But if you're in a weird situation where you are not allowed to install mysqlnd, it is still possible to get your data into an associative array without it. Try using the code in this answer
Mysqli - Bind results to an Array