I am trying to use mySQLi for the first time. I have done it in case of loop. Loop results are showing but i am stuck when i try to show 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)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
?>
<?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);
?>
<?php // echo 'Name' .$row['ssfullname'] . 'email' . $row['ssemail'] . "\n"; ?>
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
<?php
// end loop
}
?>
Above code is fine in case of loop. Now how do i show single record, any record, name or email, from first row or whatever, just single record, how would i do that? In single record case, consider all above loop part removed and lets show any single record without loop.
So, just do as you said: remove the loop from the code, leaving the rest as is:
By the way, although using raw api while learning is okay, consider using some database abstraction library in the future.
It will turn all your database code into 3 lines:
Use
mysqli_fetch_row()
. Try this,There is an example in php.net, is the #4.
http://php.net/manual/en/mysqli.quickstart.statements.php
If you assume just one result you could do this as in Edwin suggested by using specific users id.
OR as "Your Common Sense" which selects just one user.
Nothing really different from the above except for PHP v.5