Single result for database using mysqli
P粉226642568
P粉226642568 2023-08-29 13:20:44
0
2
457

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.

   Name:  
Email:

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粉226642568
P粉226642568

reply all (2)
P粉321676640

Usemysqli_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'];
    P粉675258598

    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:

      $row = $result->fetch_assoc();
    • If you only need one value, starting with PHP 8.2:

      $value = $result->fetch_column();
    • Or for older versions:

      $value = $result->fetch_row()[0] ?? false;

    Here are complete examples of different use cases

    Variables used in queries

    When you want to use variables in a query, you must useprepared statements. For example, let's say we have a variable$id:

    PHP >= 8.2

    // get a single row $sql = "SELECT fullname, email FROM users WHERE id=?"; $row = $conn->execute_query($query, [$id])->fetch_assoc(); // in case you need just a single value $sql = "SELECT count(*) FROM users WHERE id=?"; $count = $conn->execute_query($query, [$id])->fetch_column();

    Old PHP version:

    // get a single row $query = "SELECT fullname, email FROM users 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(); $count = $result->fetch_row()[0] ?? false;

    A detailed explanation of the above process can be found in myarticle. As to why it must be followed, see this famousquestion

    There are no variables in the query

    In your case, if no variables are used in the query, you can use thequery()method:

    $query = "SELECT fullname, email FROM users 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;
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!