Get a single result from database using mysqli
P粉156532706
2023-08-21 22:42:04
<p>This is my first time trying to use mySQLi. I've done this in the case of a loop. The results of the loop show up, but when I try to show a single record it gets stuck. Below is the loop code, it works. </p>
<pre class="brush:php;toolbar:false;"><?php
// Connect to database
$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 the 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 can I display a single record, any record like name or email, from the first row or whatever, just a single record, how can I do this?
In case of single record, consider removing the above loop part and let us display any single record without using loop. </p>
Use
mysqli_fetch_row()
. Try this:When only one result is needed, there is no need to use a loop. Get the row directly.
If you need to obtain the entire row of data as an associative array:
If only one value is required, starting with PHP 8.2:
Or for older versions:
Here are complete examples of different use cases
Variables used for query
When using variables in a query, prepared statements must be used. For example, let's say we have a variable
$id
:PHP >= 8.2
Older versions of PHP:
A detailed explanation of the above process can be found in my article . The reasons why this process must be followed are explained in this famous Question
There are no variables in the query
In your case, there are no variables to use in the query, you can use the
query()
method: