Page 1 of 1

comparing query result to variable [SOLVED]

Posted: Tue Sep 18, 2007 5:25 am
by h123z
I'm having trouble retrieving the result of a query:

$a= "SELECT textfield FROM table WHERE key = $variable";
$b= mysql_query($a) or die("Query failed: " . mysql_error() . "$a<br>");
$c= mysql_fetch_array($b);
if ($c != $textfield){et cetra}

My if statement isn't working- when i printed the result of $c to debug, the result was "Array". there should only be one result, since field "key" is a key.

Posted: Tue Sep 18, 2007 6:46 am
by mezise
Hi,

please read the manual: http://php.net/mysql_fetch_array

Michal

Posted: Tue Sep 18, 2007 6:52 am
by h123z
I did- seems like this should work, but it doesn't.
Can anyone help more specifically?
Thanks

Posted: Tue Sep 18, 2007 8:01 am
by mezise
Result of mysql_fetch_array is an array or a boolean false, as says the manual.
So $c variable in line:

Code: Select all

$c= mysql_fetch_array($b);
returns an array or boolean false.

1. If select statement does not return any rows, the result of this line:

Code: Select all

var_export($c);
will be

Code: Select all

false
2. If select statement returns some row, the result of this line:

Code: Select all

var_export($c);
will be e.g.:

Code: Select all

array (
  0 => 'TextValue',
  'textfield' => 'TextValue',
)
So to get the value of textfield you need to get it from $c array, e.g.:

Code: Select all

$getTextfield = $c['textfield'];
3. If your $textfield variable is a string you cannot (at least shouldn't) compare a boolean or an array to a string in line:

Code: Select all

if ($c != $textfield){et cetra}
Please read manuals more carefully.

Michal

Posted: Tue Sep 18, 2007 8:28 am
by CoderGoblin
If you only need the returned field array referenced by the fieldname you may want to look at mysql_fetch_assoc. The only real difference is the amount of information returned but save where you can.