Friday, 31 August 2018

Having trouble working with associative array in php with MySQL

I've got the following PHP code working with MySQL,

What I want to do is that for each $row, I would like to put the value in either ['name'] column or ['desc4'] column to the $encode[] for sending it back to javascript for processing.. this doesn't seem to be working (e.g. only returning results of else statement in the while loop), can anyone please help?
To be more clear, there are mix of values from column 'name' and 'desc4' so Im expecting to see mixed results from the select statements but it seems to me that it never goes into the 'if' statement in the while loop.
Is there anyway to check if $row contains a particular column name?
$qTerms=explode(' ', $q);
$q_bits = array();
$q_bits2 = array();
foreach ($qTerms as $term){
    $term = sql_prep(trim($term));
    if(!empty($term)){
        $q_bits[] = "name LIKE '%{$term}%'";
    }
}

foreach ($qTerms as $term2){
    $term2 = sql_prep(trim($term2));
    if(!empty($term2)){
        $q_bits2[] = "desc4 LIKE '%{$term2}%'";
   }
}

$query  = "SELECT name FROM nutrients ";
$query .= "WHERE ".implode(' AND ', $q_bits);
$query .= " UNION ALL ";
$query .= "SELECT name FROM supplements ";
$query .= "WHERE ".implode(' AND ', $q_bits);
$query .= " UNION ALL ";
$query  = "SELECT desc4 FROM measures ";
$query .= "WHERE ".implode(' AND ', $q_bits2);

$result = mysqli_query($connection, $query);
if(!$result){
    die("Database query failed: ".mysqli_connect_error()."(".mysqli_connect_errno().")");
}

while($row = mysqli_fetch_assoc($result)){
    //$encode[] = $row['name'];
    if (in_array('name', $row)) {
        $encode[] = $row['name'];
    } else {
        $encode[] = $row['desc4'];
    }
}
mysqli_free_result($result);
echo json_encode($encode);


It looks as if the column name from the union statement is different from "name". Insert a var_dump($row); in the while loop to check the right column name; you won't need the if statement. You could also wrap your query in a select and give a proper name to the column, or don't use assoc at all, use simple array insead.
Edit I have found the issue, you have missed the concatenation period (.) when building the query at this line:
$query  = "SELECT desc4 FROM measures ";

0 comments:

Post a Comment