tags:

views:

53

answers:

2

Hi there!

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.

+1  A: 

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
}
alex
This is the simplest solution but something is wrong because it throws errors on queries that worked fine before. :(
fabrik
Can you post some of the code that is now erroring ?
alex
A: 

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'];
}
VolkerK
Gotcha! Thanks for the help that was the problem! Otherwise what is the point in mysql_result when mysql_fetch_array is working better?
fabrik
I almost always use fetch_array, the only exception are queries that are guaranteed to return exactly one record and one or maybe two fields (or fail completely), like e.g. SELECT Count(*) FROM xyz. In that case I sometimes use mysql_result() ..."have used" since I don't use php/mysql any more but pdo ;-)
VolkerK
Thanks for the explanation. Yes, COUNT is a typical mysql_result-query type and i thought i can reduce MySQL's load if i'm using mysql_result as often as i can. My fault is the site in question is heavily using mysql_result so i need to check my queries to eliminate conflicts caused by different query methods.
fabrik
The difference between mysql_result() and fetch_array() when fetching rows with one field each should be negligible. If you have rows with more fields mysql_result() is even a bit slower - still a tiny amount only. And if you're using mysql_query() the mysql server isn't involved in mysql_result() or fetch_array() at all because the complete result set is transferred server->client before the function returns.
VolkerK