Jump to content

Array comparisons with MySQL array and a php variable


Recommended Posts

After looking around for about an hour on various sites, I can't seem to find a direct answer, only how to grab the entire array etc...

 

I'm trying to find out how to compare a variable with a member of an array.

 

Doing something similar to

$idcheckx = mysql_query("SELECT id FROM inventory WHERE owner = '$user_name'");

$idchecky = mysql_fetch_assoc($idcheckx);

 

would create an array with all the id's pertaining to the user...

 

How would I check if a variable, let's say $this_id = "3";  exists in the $idchecky array?

 

Thank you in advance,

-D

$idcheckx = mysql_query("SELECT id FROM inventory WHERE owner = '$user_name'");
$idchecky = mysql_fetch_assoc($idcheckx);
$thisid = 3;
foreach($idchecky as $name => $id) {
    if(in_array($thisid, $id)) {
        echo "Found a match where id is ".$id;
    }
}

1) A call to mysql_fetch_assoc() fetches ONE row from the result set.

2) Since your query is only selecting id, $idchecky will be an array with one element $idchecky['id'] that will contain whatever your id column consists of for the specific owner = that matched the WHERE clause.

 

What exactly does the data in your table look like (post at least two rows that should match a specific owner.)

 

One of the great points of using a database is you only retrieve the information you are interested in. If you find yourself looping through the result of a query searing for a value, you are not using the database effectively. If you only want the row(s) that have a specific value, such as id = $this_id, then you would include that comparison in the WHERE clause in the query.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.