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
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
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";
}
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;
}
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
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
}
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);