Single result for database using mysqli
P粉226642568
2023-08-29 13:20:44
<p>This is my first time trying mySQLi. I've done it in a loop. The loop results are showing, but when I try to show a single record, I get stuck. This is the loop code in action. </p>
<pre class="brush:php;toolbar:false;"><?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
}
?></pre>
<p>How do I display a single record, any record, name or email, from the first row or whatever, just a single record, how do I do that?
In case of single record, consider removing all the above looping parts and let us display any single record without looping. </p>
Use
mysqli_fetch_row()
. Try this,Loops should not be used when only a single result is required. Just get the row now.
If you need to extract the entire row into an associative array:
If you only need one value, starting with PHP 8.2:
Or for older versions:
Here are complete examples of different use cases
Variables used in queries
When you want to use variables in a query, you must use prepared statements. For example, let's say we have a variable
$id
:PHP >= 8.2
Old PHP version:
A detailed explanation of the above process can be found in my article . As to why it must be followed, see this famous question
There are no variables in the query
In your case, if no variables are used in the query, you can use the
query()
method: