php sql with multiple selects not working - php

The following code is giving me this error:
Call to undefined method mysqli_stmt::get_result() on line 21.
I don't understand how this object works and why I can do the first database call but not the second.
<?php
header('Content-Type: application/json');
include_once 'do_dbConnect.php';
include_once 'functions.php';
sec_session_start();
//identify who took the last call
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT MAX(dateOfCall), id FROM call")) { //setup the query statement
$stmt->execute(); //execute the statement
$result = $stmt->get_result(); //get the results
$row = $result->fetch_assoc(); //get the first row
$user_id = $row['id']; //get the id column
}
//identify how many team members there are
if ($stmt->prepare("SELECT id FROM teamMembers")) { //setup the query statement
$stmt->execute(); //execute the statement
$result = $stmt->get_result(); //get the results
$memberCount = $result->num_rows;
}
//get next user
if ($stmt = $mysqli->prepare("SELECT * FROM teamMembers WHERE id = (? + 1) % ?")) { //setup the query statement
$stmt->bind_param('ii', $user_id, $memberCount);
$stmt->execute(); //execute the statement
$result = $stmt->get_result(); //get the results
$row = $result->fetch_assoc(); //get the first row
$next_user_id = $row['id']; //get the id column
$next_user_name = $row['username'];
}
$stmt->close();
//get the next call taker from the teamMember table
echo json_encode($row);
?>

Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver... if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH!
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.fetch.php

Related

Why can't I get data from SQL row using PHP prepared statements?

Connection is good. I can insert into the database, and check if a row exists by checking if results > 0, but I can not select row data. The $email's being tested are in the database.
Ex 1.
require 'connection/connection.php';
$email = "sample#sample.com";
$sql = "SELECT * FROM users WHERE user_email=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
echo $user['user_name'];
Ex. 2
$email = "james#james.com";
$sql = "SELECT * FROM users WHERE user_email=?";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
After inserting an echo after every line one by one, this is as far as it gets. If an echo statement is placed after the next line it will not appear.
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION['active_user_id'] = $row['user_id'];
} else {
header("Location: https://example.com/");
exit();
}
The problem was fixed through cPanel. I had to switch from "mysqli" to "nd_mysqli." This fixed the problem right away.
I found the instructions to do this here https://www.plus2net.com/php_tutorial/mysqli_mysqlnd.php
I hope this helps others with the same problem.

why iam getting an error related to bind_result in error_log file and how to fix it? [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
Iam getting this error
[07-Sep-2017 11:48:47 UTC] PHP Warning: mysqli_stmt::bind_result():
Number of bind variables doesn't match number of fields in prepared
statement
$stmt = $con->prepare("SELECT * FROM table where Id =?");
$stmt->bind_param("s", $_POST['Id']);
$stmt->execute();
$result = $stmt-> bind_result($Id);
$numRows = $result->num_rows;
if($numRows > 0) {
if($row = $result->fetch_assoc())
{
$Taxname=$row['TaxName'];
$Tid=$row['Id'];
}}
You need to alter your query. Instead of * you need to instead opt for picking out the data you actually want from the database.
For example, if the table table has columns Id,TaxName then you would execute like so:
<?php
$sqlData = array();
$stmt = $con->prepare("SELECT Id,TaxName FROM table where Id =?");
$stmt->bind_param("i", $_POST['Id']); //id is an integer? this should be i instead of s
$stmt->execute();
$stmt->store_result(); //store the result, you missed this
$stmt-> bind_result($Id,$TaxName); //bind_result grabs the results and stores in a variable
$numRows = $stmt->num_rows; //see the correction I made here
if($numRows >0){
while ($stmt->fetch()) { //propper way of looping thru the result set
$sqlData [] = array($Id,$TaxName);
//assoc array would look like:
//$sqlData [] = array("Id" =>$Id,"TaxName" => $TaxName);
}
}
$stmt->close(); //close the connection
?>
Then you would have an array of results that you can use after you've finished with mysqli queries.
Hope this helps you understand it a bit more.
$stmt = $con->prepare("SELECT Id,TaxName FROM table where Id =?");
$stmt->bind_param("s", $_POST['Id']);
$stmt->execute();
$result = $stmt-> bind_result($Id,$TaxName);
$stmt->store_result();
$numRows = $stmt->num_rows;
if($numRows > 0) {
while( $result->fetch_assoc())
{
$newid = $Id;
$newtaxname= $TaxName;
}
print_r($newid)."<br>";
print_r($newtaxname);
}
This code will give you the answer without any warnings.
Reference : http://php.net/manual/en/mysqli-stmt.bind-result.php
mysqli_stmt::bind_result — Binds variables to a prepared statement for
result storage

Not Getting Row From Mysqli

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
}

PHP PDO how do i include fetch assoc and numrows

trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.

How to remove the fatal error when fetching an assoc array

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

Categories