Domanda

i am new in php, so i need help with this:

i have a values cell like 1,2,3,4,5

For example i need to check if value 3 is in that cell.

So, here is my code:

$article = $db->query("SELECT users FROM products WHERE id = $product_id");
while ($data = $article->fetch_object()) {
$users = $data->users;
}

$number_that_i_need_to_check_if_is_in_string = 3;
$users = explode(',',$users);
foreach ($users as $specific) {
    //i dont know what to do here...
}

And i dont know how to check is that number 3 in that string...

thx in advance.

È stato utile?

Soluzione 2

You don't need the foreach loop. Once you have all the values in an array you can just use the in_array() function: http://us3.php.net/in_array

Also there is a problem with your while loop. If there are multiple rows returned the way you have it written will just overwrite each value with the next so $users will only hold one value and you wont be able to explode it.

What you could do is just read all the values directly into an array by changing that line to the following:

$users[] = $data->users;

then

if(in_array(3,$users)){
    .....
}

Altri suggerimenti

Using your code, you can do this

foreach($users as $specific) {
  if($number_that_i_need_to_check_if_is_in_string == $specific) {
    //do something here.
  }
}

There are much better ways of doing this, including writing the query to do the search for you, or using array_search.

You can use FIND_IN_SET mysql function like this

$article = $db->query("SELECT users FROM products WHERE id = $product_id AND FIND_IN_SET(3, users)");

This query will get you all the rows where id=$product_id and users field has 3 in it.

You could either include it in the query

SELECT users FROM products WHERE id=$product_id AND FIELD_IM_CHECKING=$number_that_i_need_to_check_if_is_in_string

or...

use the string you're looking for as an index for an array.

while($data=$article->fetch_object()){
 $users[$data->FIELD_IM_CHECKING][]=$data->users;

You end up with an array with the value you're looking for as the index. So $users[3] would be all users with '3' in the field you're looking for...

please do make a little better question next time. Since you're not specific in the data you have and query my answer seems pretty vague as well...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top