My question is how can I be sure of a row that I'd like to return is exists? I don't want to suppress it with PHP's @ option or count rows before every query to find out the row is exists or not.
So there's a simple query like this:
"SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
and the table cannot contain the row with id 234
.
You're probably using mysql_result() to fetch the fields. Consider mysql_fetch_array instead. It returns FALSE if there are no more rows to fetch.
<?php
$mysql = mysql_connect('..', '..', '..') or die(mysql_error());
mysql_select_db('..', $mysql) or die(mysql_error());
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$result = mysql_query($query, $mysql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo 'no such record';
}
else {
echo $row['title'], ' ', $row['id'];
}
You don't have to count rows before every query - generally you do it after.
What about something like this
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
// do something because it was found
}