2

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>";
?>
3
  • 3
    WHERE author='" . implode ($author) ."'"; WTF?!? Have you ever come across SQL's IN Commented Nov 6, 2013 at 19:16
  • @MarkBaker Actually, I am VERY new at this, so I must say, no I have not. Any suggestions would be appreciated. I will check it out though. Commented Nov 6, 2013 at 19:18
  • SQL IN Operator Commented Nov 6, 2013 at 19:25

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

hihi! :) implode() again.. however, you might give an example for a prepared statement here...
I just tried this, but I still only get results for one item in array.
@JeremyTyler: Can you try to echo $query; before execution and post the output?
@JeremyTyler: Glad to have been of help :)
1

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);
}

Comments

0

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)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.