Mysqli fetch single row php

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).

❮ PHP MySQLi Reference

Example - Object Oriented style

Fetch rows from a result-set:

$mysqli = new mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";

if ($result = $mysqli -> query($sql)) {
  while ($row = $result -> fetch_row()) {
    printf ("%s (%s)\n", $row[0], $row[1]);
  }
  $result -> free_result();
}

$mysqli -> close();
?>


Look at example of procedural style at the bottom.


Definition and Usage

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.


Syntax

Object oriented style:

$mysqli_result -> fetch_row()

Procedural style:

Parameter Values

ParameterDescription
result Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Technical Details

Return Value:Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result set
PHP Version:5+

Example - Procedural style

Fetch rows from a result-set:

$con = mysqli_connect("localhost","my_user","my_password","my_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}

$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";

if ($result = mysqli_query($con, $sql)) {
  // Fetch one and one row
  while ($row = mysqli_fetch_row($result)) {
    printf ("%s (%s)\n", $row[0], $row[1]);
  }
  mysqli_free_result($result);
}

mysqli_close($con);
?>



❮ PHP MySQLi Reference


mysqli_fetch_row

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_row -- mysqli_fetch_rowFetch the next row of a result set as an enumerated array

Description

Object-oriented style

public mysqli_result::fetch_row(): array|null|false

mysqli_fetch_row(mysqli_result $result): array|null|false

Note: This function sets NULL fields to the PHP null value.

Return Values

Returns an enumerated array representing the fetched row, null if there are no more rows in the result set, or false on failure.

Examples

Example #1 mysqli_result::fetch_row() example

Object-oriented style

mysqli_report

(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost""my_user""my_password""world");$query "SELECT Name, CountryCode FROM City ORDER BY ID DESC";$result $mysqli->query($query);/* fetch object array */
while ($row $result->fetch_row()) {
    
printf("%s (%s)\n"$row[0], $row[1]);
}

Procedural style

mysqli_report

(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);
$mysqli mysqli_connect("localhost""my_user""my_password""world");$query "SELECT Name, CountryCode FROM City ORDER BY ID DESC";$result mysqli_query($mysqli$query);/* fetch associative array */
while ($row mysqli_fetch_row($result)) {
    
printf("%s (%s)\n"$row[0], $row[1]);
}

The above examples will output something similar to:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

Stephen

15 years ago

It's worth noting that the MySQLi functions (and, I presume, the MySQL functions) fetch a string regardless of the MySQL data type. E.g. if you fetch a row with an integer column, the corresponding value for that column and row will still be stored as a string in the array returned by mysql_fetch_row.

sainthyoga2003 at gmail dot com

8 years ago

Note that mysqli_fetch() is deprecated but still is in PHP function list. mysqli_fetch_row() is nowadays mysql procedural style used, but is not listed in PHP functions.

evangun2001 at yahoo dot fr

15 years ago

Remember that fetch() and fetch_row() are two different things, and differ in the way to use them.

- fetch() is used on a statement (like an executed prepared statement) and needs to be used in association with bind_result().

- fetch_row() is used on a result (like the result of query()).

As a consequence, if you want to use to use fetch_row() with an executed prepared statement, first you'll have to get the result out of this statement with mysqli_store_result() or mysqli_use_result().

maillist at pnpitalia.it

18 years ago

from "README.PHP4-TO-PHP5-THIN-CHANGES"

4. Be careful when porting from ext/mysql to ext/mysqli. The following
   functions return NULL when no more data is available in the result set
   (ext/mysql's functions return FALSE).

    - mysqli_fetch_row()
    - mysqli_fetch_array()
    - mysqli_fetch_assoc()

How can I get single record in PHP?

Show activity on this post. $link = mysql_connect('localhost','root','yourPassword') mysql_select_db('database_name', $link); $sql = 'SELECT id FROM games LIMIT 1'; $result = mysql_query($sql, $link) or die(mysql_error()); $row = mysql_fetch_assoc($result); print_r($row);

How can we fetch data from database row by row in PHP?

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.

How can I get one record details in MySQL database using PHP?

Displaying records using MySQLI functions php"; // MySQL connection string $count="SELECT name,id,class,mark,sex FROM student LIMIT 10"; if($stmt = $connection->query($count)){ echo ""; while ($row = $stmt->fetch_assoc()) { echo "

What does mysql_fetch_row () function do?

mysql_fetch_row() retrieves the next row of a result set: When used after mysql_store_result() , mysql_fetch_row() returns NULL if there are no more rows to retrieve.