Question

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>";
?>
Was it helpful?

Solution

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.

OTHER TIPS

You need to use IN condition in your SQL Query

$query.=" WHERE author IN (" . implode (',',$author) .")";

SQL IN Condition

if author is string your code will be

 if (isset($author)){
$query . = "("
foreach ($author as $value)
{
    $query .= "'".$value."',";
}
$query = substr($query,0,-1);
$query .= ")";

    print_r ($author);
}

probably author names will be string and you should format it it like below

    IN ('author1', 'author2')

A php function which will help you

function quote($str) {
    return sprintf("'%s'", $str);
}
$authors = array('author1', 'author2', 'author3');
WHERE author IN (implode(',', array_map('quote', $authors)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top