Alex Caron Alex Caron - 2 months ago 6
MySQL Question

Match rows against elements in an array

I have a sql request to do with a php array to find all the occurrences of a search bar.

I can't get this done. This is my code :

$texte = $_POST['texte'];
$texte = explode(" ", $texte);
$query_parts = array();

//Proximité
foreach ($texte as $value) {
$value = "%".$value."%";
}



$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE ':texte'";
$req = $bd->requete_obj($sql, array('texte'=>$texte));

while($select = $req->fetch()){
error_log('Test');
}

Answer

Your foreach-loop does not actually modify the variables, because they are passed by Value - meaning a copy. to modify them, you have to pass them by reference:

foreach ($texte as &$value) {
    $value = "%".$value."%";
}

that way, the actual values in your array are being manipulated.

secondly: you can not give your database an array as parameter. instead, you could loop through the array. if you implement that in your first loop, you don't even have to use references anymore:

$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE :texte";
foreach ($texte as $value) {
    $value = "%".$value."%";
    $req = $bd->requete_obj($sql, array('texte'=>$value));
    while($select = $req->fetch()){
        error_log('Test');
    }
}
Comments