Monday 3 September 2018

Array does not return anything from mysql if more than one selected value

How do I get all the results of my query to show? If my $author prints as Array ( [0] => 1 ) the query pulls correct data. However, if my $author prints as Array ( [0] => 1 [1] => 8 ) or any combination of values received from my form, then it returns empty.

The array prints correctly, so I am moving from that point forward and assuming the problem is the query but cannot figure it out.
$query = "SELECT * FROM estudos";
if (isset($author)){
    $query.=" WHERE author='" . implode ($author) ."'";
    print_r ($author);
}

Here is my php and html...
$results=$dbclient->query($query) or die(mysqli_error());

<?php
while($row=mysqli_fetch_array($results))
    echo"<tr><td class='name'>$row[name]</td>";
?>


You're missing the glue parameter for implode(). Without that, your $query would look something like this:
SELECT * FROM estudos WHERE author='FooBarBaz'

This is a syntactically valid SQL query, but it doesn't do what you want.
You're probably looking for the IN clause.
$query .= " WHERE author IN (" . implode (',', $author) .")";

Note that I haven't fixed the SQL injection vulnerabilities in your query. I recommend you switch to MySQLi or PDO and start using parameterized queries to be safe from SQL injection.

0 comments:

Post a Comment