php bind_result - php

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();

Related

Creating a chart in PHP by using a count sql function [duplicate]

I am trying to use mySQLi for the first time. I have done it in the case of loop. Loop results are showing but I am stuck when I try to show a single record. Here is loop code that is working.
<?php
// Connect To DB
$hostname="localhost";
$database="mydbname";
$username="root";
$password="";
$conn = mysqli_connect($hostname, $username, $password, $database);
?>
<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
<?php
/*Loop through each row and display records */
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
<?php
// end loop
}
?>
How do I show a single record, any record, name, or email, from the first row or whatever, just a single record, how would I do that?
In a single record case, consider all the above loop part removed and let's show any single record without a loop.
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
Variables to be used in the query
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id:
$query = "SELECT ssfullname, ssemail FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
No variables in the query
In your case, where no variables to be used in the query, you can use the query() method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
Use mysqli_fetch_row(). Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
Instead of using $row = $query->fetch(); try to use:
$result = $query->get_result();
$row=$result->fetch_assoc();
every time you can check if you get data from mysql tables by displaying them using:
var_export( $row['put your column name here'] );
The first answer will do the job but in this case you don't need to loop the result.
$row = $result->fetch_row();
Just echo the column
echo $row['column'];
This should do the trick
As of PHP 8.1, mysqli_result::fetch_column() is available
You can use mysqli_result::fetch_column() to fetch a single scalar value from the result set.
The new method accepts 0-based position of the column you want to read. The default value is 0.
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->execute([$id])
$result = $stmt->get_result();
$ssemail = $result->fetch_column(1);
Beware that this method will move the internal pointer to the next row, just like the other fetch_* methods do. When it reaches the end, it will return false. Therefore, in the above example, you would be better off using fetch_assoc() to fetch the entire row into an array.
It can also be used with mysqli::query() for SQL statements without parameters.
$query = "SELECT count(*) FROM userss";
$count = $conn->query($query)->fetch_column();

Not sure how to echo out the Selected data from mysql

$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
echo "Exists";
}
Instead of echoing out Exists, I want it to echo out nameData. How can I go about doing that?
First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
So there are two approaches to display nameData:
Method(1):
First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
}else{
echo "No result found";
}
Method(2):
First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
$row = $result->fetch_array()
echo $row['nameData'];
}else{
echo "No result found";
}
I think you can below code i hope your query is working fine it returns result properly then you can use below code.
$stmt->bind_result($nameData);
if ($stmt->fetch()) {
printf ("%s\n", $nameData);
}
Note that affected_rows won't do anything useful here.
However, nor you don't need num_rows as well (and therefore store_result too)
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;
Considering all that hassle, even without useless functions, you may find PDO a way better approach:
$stmt = $pdo->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->execute($query);
echo->$stmt->fetchColumn();

mysql_result to mysqli to get a single value [duplicate]

I am trying to use mySQLi for the first time. I have done it in the case of loop. Loop results are showing but I am stuck when I try to show a single record. Here is loop code that is working.
<?php
// Connect To DB
$hostname="localhost";
$database="mydbname";
$username="root";
$password="";
$conn = mysqli_connect($hostname, $username, $password, $database);
?>
<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
<?php
/*Loop through each row and display records */
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
<?php
// end loop
}
?>
How do I show a single record, any record, name, or email, from the first row or whatever, just a single record, how would I do that?
In a single record case, consider all the above loop part removed and let's show any single record without a loop.
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
Variables to be used in the query
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id:
$query = "SELECT ssfullname, ssemail FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
No variables in the query
In your case, where no variables to be used in the query, you can use the query() method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
Use mysqli_fetch_row(). Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
Instead of using $row = $query->fetch(); try to use:
$result = $query->get_result();
$row=$result->fetch_assoc();
every time you can check if you get data from mysql tables by displaying them using:
var_export( $row['put your column name here'] );
The first answer will do the job but in this case you don't need to loop the result.
$row = $result->fetch_row();
Just echo the column
echo $row['column'];
This should do the trick
As of PHP 8.1, mysqli_result::fetch_column() is available
You can use mysqli_result::fetch_column() to fetch a single scalar value from the result set.
The new method accepts 0-based position of the column you want to read. The default value is 0.
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->execute([$id])
$result = $stmt->get_result();
$ssemail = $result->fetch_column(1);
Beware that this method will move the internal pointer to the next row, just like the other fetch_* methods do. When it reaches the end, it will return false. Therefore, in the above example, you would be better off using fetch_assoc() to fetch the entire row into an array.
It can also be used with mysqli::query() for SQL statements without parameters.
$query = "SELECT count(*) FROM userss";
$count = $conn->query($query)->fetch_column();

Anything wrong with this MySQL query?

$stmt = $connection->prepare("SELECT id FROM articles WHERE position =? LIMIT 1");
$stmt-> bind_param('i',$call );
$stmt->execute();
$result = $stmt->fetch();
$oldpostid = $result;
$stmt->close();
I don't see anything wrong with it, but it is returning 1 or nothing. $call is set and integer. I tried this too:
$stmt = $connection->prepare("SELECT * FROM articles WHERE position =? LIMIT 1");
$oldpostid = $result['id'];
Assuming this is all working you need to bind the result variables as well. mysqli_stmt_fetch returns a boolean:
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$oldpostid = $id;
You seem to be mixing mysqli & PDO. The first line is PDO
$stmt = $connection->prepare("SELECT id FROM articles WHERE position =? LIMIT 1");
The next line is mysqli
$stmt-> bind_param('i',$call );
Should be for PDO the unnamed variables in place holder Manual Example 4
$stmt-> bindParam(1,$call );
$stmt->execute();
OR using array
$stmt->execute(array($call));

Single result from database using mysqli

I am trying to use mySQLi for the first time. I have done it in the case of loop. Loop results are showing but I am stuck when I try to show a single record. Here is loop code that is working.
<?php
// Connect To DB
$hostname="localhost";
$database="mydbname";
$username="root";
$password="";
$conn = mysqli_connect($hostname, $username, $password, $database);
?>
<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
<?php
/*Loop through each row and display records */
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
<?php
// end loop
}
?>
How do I show a single record, any record, name, or email, from the first row or whatever, just a single record, how would I do that?
In a single record case, consider all the above loop part removed and let's show any single record without a loop.
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
Variables to be used in the query
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id:
$query = "SELECT ssfullname, ssemail FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
No variables in the query
In your case, where no variables to be used in the query, you can use the query() method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
Use mysqli_fetch_row(). Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
Instead of using $row = $query->fetch(); try to use:
$result = $query->get_result();
$row=$result->fetch_assoc();
every time you can check if you get data from mysql tables by displaying them using:
var_export( $row['put your column name here'] );
The first answer will do the job but in this case you don't need to loop the result.
$row = $result->fetch_row();
Just echo the column
echo $row['column'];
This should do the trick
As of PHP 8.1, mysqli_result::fetch_column() is available
You can use mysqli_result::fetch_column() to fetch a single scalar value from the result set.
The new method accepts 0-based position of the column you want to read. The default value is 0.
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->execute([$id])
$result = $stmt->get_result();
$ssemail = $result->fetch_column(1);
Beware that this method will move the internal pointer to the next row, just like the other fetch_* methods do. When it reaches the end, it will return false. Therefore, in the above example, you would be better off using fetch_assoc() to fetch the entire row into an array.
It can also be used with mysqli::query() for SQL statements without parameters.
$query = "SELECT count(*) FROM userss";
$count = $conn->query($query)->fetch_column();

Categories