Mysqli object oriented can store a row of data? - php

I am actually using this to store and know some fields of my database:
$conn_2 = dbConnect();
$stmt2 = $conn_2->prepare("SELECT firstname, lastname, type FROM BrokerMaster.users WHERE email = ?");
$stmt2->bind_param("s", $email);
$stmt2->execute();
$stmt2->bind_result($firstname, $lastname, $type);
while ($stmt2->fetch()) {
printf("%s %s %s\n", $firstname, $lastname, $type);
}
But I would like to do something like:
$stmt2 = $conn_2->prepare("SELECT * FROM BrokerMaster.users WHERE email = ?");
$stmt2->bind_param("s", $email);
$stmt2->execute();
$stmt2->bind_result($result); //??
while ($row = $stmt2->fetch()) {
$firstname = $row["firstname"]
}
I couldn't find a way to do it object oriented. The problem I found is that the $result is not a mysqli_result class (if I am not wrong) and unlike query() the execute() and bind_results() don't create it. (I also couldn't manage to use this answer
What are my mistakes (or misunderstandings)? How can I do it?

Sure you can, but you would use fetch_assoc() function.
So you use fetch_assoc() on the mysqli_result. Doing it in a while loop, will continue cycling until there are available rows.
while ($row = $result->fetch_assoc()) {
//Use $row["column_field"];
}
Edit
It happens that we can't get result object straight from a prepared statement.
$stmt2->store_result();
$result = $stmt2->get_result();
Now you should be able to use fetch_assoc() over your mysqli_result

Related

Unable to return array from SQL, only returning mysqli_stmt

I've been doing SQL for over a year now, and have became completely stuck. For some reason, i'm not able to return any values from this table as I get the error
mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, mysqli_stmt given
I'm completely floored as to why this is happening, as i've used these kind of queries in the past
The code i'm using is
$user = "testuser";
$q = $conn->prepare("SELECT * FROM users WHERE username = ?");
$q->bind_param("s", $user);
$q->execute();
while($row = mysqli_fetch_array($q))
var_dump($row);
If I do var_dump($q), then I get an object object(mysqli_stmt)#3 (10) with no errors and the correct amount of fields. I'm just not able to read anything from this for some reason.
Thanks!
You need to call a get_result() before you can fetch your data
$user = "testuser";
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
var_dump($row);
}
PS. better to use fetch_assoc() instead of fetch_array()

Mysqli prepared statement get multiple rows from multiple columns on Count condition [duplicate]

I'm currently working on a login script, and I got this code:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
if ($selectUser->num_rows() < 0)
echo "no_user";
else
{
$user = $selectUser->fetch_assoc();
echo $user['id'];
}
Here's the error I get:
Fatal error: Uncaught Error: Call to undefined method
mysqli_stmt::fetch_assoc()
I tried all sorts of variations, like:
$result = $selectUser->execute();
$user = $result->fetch_assoc();
and more... nothing worked.
That's because fetch_assoc is not part of a mysqli_stmt object. fetch_assoc belongs to the mysqli_result class. You can use mysqli_stmt::get_result to first get a result object and then call fetch_assoc:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
$result = $selectUser->get_result();
$assoc = $result->fetch_assoc();
Alternatively, you can use bind_result to bind the query's columns to variables and use fetch() instead:
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->bind_result($id, $password, $salt);
$selectUser->execute();
while($selectUser->fetch())
{
//$id, $password and $salt contain the values you're looking for
}
1) you need the mysqlInd driver.
The variable $db 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!
Alternative try this
$selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$selectUser->bind_param('s', $username);
$selectUser->execute();
$selectUser->bind_result($id, $password,$salt);
while ($selectUser->fetch()) {
printf("%s %s %s\n", $id, $password,$salt);
}
for more info about this Reference link
Now talk of alternatives.
PDO, unlike mysqli, never have a problem like this. It can fetch you an array out of a prepared statement without the need of installing any additional modules.
$stmt = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if (!$user) {
echo "no_user";
} else {
echo $user['id'];
}
See, it works exactly the way you would expect and require two times less code to write. Not to mention other wonderful features.

Converting mysql functions to mysqli prepared statment keeping the same output

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){}

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

php bind_result

I have this sequence of code:
$connection = new mysqli('localhost','root','','db-name');
$query = "SELECT * from users where Id = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($this->id,$this->cols);
$stmt->fetch();
$stmt->close();
$connection->close();
The problem is that the "SELECT" might give a variable number of columns, which i retain in $this->cols. Is there any possibility to use bind_result with a variable number of parameters?...or any alternative to the solution.
if you are lucky enough to run PHP 5.3+, mysqli_get_result seems what you want.
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();

Categories