comparing query result to variable [SOLVED]

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
h123z
Forum Newbie
Posts: 7
Joined: Tue Sep 18, 2007 5:18 am

comparing query result to variable [SOLVED]

Post 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.
Last edited by h123z on Wed Sep 19, 2007 6:38 am, edited 1 time in total.
mezise
Forum Newbie
Posts: 17
Joined: Tue Sep 18, 2007 4:38 am

Post by mezise »

Hi,

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

Michal
h123z
Forum Newbie
Posts: 7
Joined: Tue Sep 18, 2007 5:18 am

Post by h123z »

I did- seems like this should work, but it doesn't.
Can anyone help more specifically?
Thanks
mezise
Forum Newbie
Posts: 17
Joined: Tue Sep 18, 2007 4:38 am

Post 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
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
Post Reply