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 t
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");
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
$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']
Use LIMIT 1. its easy.
$rows = $db->query("select id from games LIMIT 1");
$row = $rows->fetch_object();
echo $row->id;
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];
}
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)