How can I find a number in a string in PHP?

0

I have a field in a table called personal and the data that it saves is a string of numbers delimited by commas, ex:

10,32,43,55,2,45

At the moment of wanting to make a query to find a specific employee I want to use this function:

    foreach ($ids as $id):
            $res = mysqli_query($link, "SELECT id FROM projectP WHERE personal LIKE '%$id%'");
            $row = mysqli_fetch_assoc($res);
            var_dump($row);
    endforeach;

But if the employee is 44 and in the string there is a 4 only, tmb finds it and I need you only to find the ones that are 44, any ideas?

    
asked by Fernando Garcia 30.10.2018 в 19:20
source

3 answers

0

It is not recommended to save lists separated by commas in the database. But if you can not or it's very difficult to separate them, you can do it by adding more logic and using explode like this:

foreach ($ids as $id):
        $res = mysqli_query($link, "SELECT id FROM projectP WHERE personal LIKE '%$id%'");
        $row = mysqli_fetch_assoc($res);
        $valores = explode(',', $row['id']);
        if (in_array($id, $valores) {
            var_dump($row);
        }
endforeach;
    
answered by 30.10.2018 в 19:28
0

You can try validating the string that you pass:

function val_number($str){
      if(preg_match('^-?\d+(?:,\d+)?$',$str)){
          return true;
      }
    return false;
}

$n1 = "239,12312,12312";
$n2 = "239,12312,12312,";
$n3 = "as239,12312,12312.";
$n4 = ",239,12312,12312";

val_number($n1);   //true
val_number($n2);   //false
val_number($n3);   //false
val_number($n4);   //false

after your query you use

$ids = explode(',', $row['id']);
foreach($ids as $r){
 echo $r == $id ? "son iguales" : "no son iguales";
}
    
answered by 30.10.2018 в 20:05
0

You have to use IN in your query sql , which is responsible for looking up records when your field personal is between the values provided:

SELECT id FROM projectP WHERE personal IN ($id)
    
answered by 30.10.2018 в 22:24