[php] Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:

SELECT id FROM games

I was trying to find an answer in the old questions, but had no luck.

This question is related to php mysql

The answer is


I could get result by using following:

$resu = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM employees1 WHERE pkint =58"));
echo ( "<br />". $resu['pkint']). "<br />" . $resu['f1'] . "<br />" . $resu['f2']. "<br />" . $resu['f3']. "<br />" . $resu['f4' ];

employees 1 is table name. pkint is primary key id. f1,f2,f3,f4 are field names. $resu is the variable shortcut for result. Following is the output:

<br />58
<br />Caroline
<br />Smith
<br />Zandu Balm

I really like the philosophy of the ezSQL database library, which wraps the native SQL methods in an easier-to-use interface.

Fetching a single value from the database is trivial:

  $id = $db->get_var("SELECT id FROM games WHERE ...");

It also makes it easy to fetch a single row, column, or set of rows.


First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);

$singleRow = mysql_fetch_array($result) 
echo $singleRow;

Edit: So sorry, forgot the database connection. Added it now


Say that you want to count the rows in an existing table:

Use mysql_result with only one parameter set to "0"

Like this:

$string = mysql_result(
          mysql_query("SELECT COUNT(*) FROM database_name.table_name ")
,0);

Put ( ` ) around database_name and table_name

var_dump($string);

// string(1) "5" //if it only has 5 records in the table

Note: if you query for something else like

SELECT * FROM database.table LIMIT 1

and the table has more than one column then you WILL NOT get an array() in your var_dump you will get the first column only


One more answer for object oriented style. Found this solution for me:

$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;

gives back just one id. Verify that your design ensures you got the right one.


at first : CREATE connection

$conn =  new mysqli('localhost', 'User DB', 'Pass DB', 'Table name');

and then get the record target :

$query = "SELECT id FROM games LIMIT 1"; // for example query
$result = $conn->query($query); // run query
if($result->num_rows){ //if exist something
    $ret = $result->fetch_array(MYSQLI_ASSOC); //fetch data
}else{
    $ret = false;
}
var_dump($ret);

$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);

I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:

$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
    echo mysql_result($r); // will output first ID
    echo mysql_result($r, 1); // will ouput second ID
}

$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");

Better if SQL will be optimized with addion of LIMIT 1 in the end:

$query = "select id from games LIMIT 1";


SO ANSWER IS (works on php 5.6.3):

If you want to get first item of first row(even if it is not ID column):

queryExec($query) -> fetch_array()[0];

If you want to get first row(single item from DB)

queryExec($query) -> fetch_assoc();

If you want to some exact column from first row

queryExec($query) -> fetch_assoc()['columnName'];

or need to fix query and use first written way :)


Use LIMIT 1. its easy.

$rows = $db->query("select id from games LIMIT 1");
$row  =  $rows->fetch_object();
echo $row->id;

Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:

$userID = mysqli_insert_id($link);

otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.

Either way, to limit your SELECT query, use a WHERE statement like this: (Generic Example)

$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];

(Specific example) Or a more specific example:

$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];

Using PDO you could do something like this:

$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');

$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
    echo $id;
}

You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');  
$db->set_charset('utf8mb4');

if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
    $id = $row[0];
}

function getSingleRow($table, $where_clause="", $column=" * ",$debug=0) {
    $SelectQuery = createQuery($table, $where_clause, $column);

    $result = executeQuery($SelectQuery,$debug);
    while($row = mysql_fetch_array($result)) {
        $row_val = $row;
    }
    return $row_val;
}

$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);

There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.

Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']


Easy way to Fetch Single Record from MySQL Database by using PHP List

The SQL Query is SELECT user_name from user_table WHERE user_id = 6

The PHP Code for the above Query is

$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= "  user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;

$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);

Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows


The easiest way is to use mysql_result. I copied some of the code below from other answers to save time.

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);

$num_rows = mysql_num_rows($result);

// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
    $value = mysql_result($result, i, 'id');
    echo 'Row ', i, ': ', $value, "\n";
}

'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:

with mysqli

$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();

with Zend Framework

//Inside the table class

$select = $this->select()->where('user_id = ?', 1);  
$row = $this->fetchRow($select);

Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:

$sql = "SELECT id FROM games LIMIT 1";  // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];

This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.