user3525134
user3525134

Reputation: 133

Searching MySQL for part of an array

Im trying to take an array of titles from the column 'list' and then get details for every title on said list.

//Get list
$r=$link->prepare('SELECT list FROM lists WHERE user=? LIMIT 1');
$r->bindValue(1,$user,PDO::PARAM_STR);
$r->execute();
$list=$r->fetchAll(PDO::FETCH_ASSOC);

//See how many titles the list has  
$list_length=count($list);

//Get details for every title   
for($i=0;$i<$list_length;$i++)
{
    $r2=$link->prepare('SELECT * FROM details WHERE title=?');
    $r2->bindValue(1,$list[$i],PDO::PARAM_STR);
    $r2->execute();
    $details=$r2->fetchAll(PDO::FETCH_ASSOC);
}
return json_encode($details);

As it is I get echoed just [].

I also get Notice: Array to string conversion in $r2->bindValue(1,$list[$i],PDO::PARAM_STR);

Upvotes: 0

Views: 113

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

  1. You have to learn to read your code, instead of asking others to do it for you.

    SELECT list FROM lists WHERE user=? LIMIT 1
    

    Look at this query. Does it looks like one that can return an array of rows?

  2. Learn SQL. And JOINS particularly

And here goes the code

$sql = 'SELECT details.*  FROM lists JOIN details on title=list WHERE user=?';
$stm = $link->prepare($sql);
$stm->execute([$user]);
json_encode($stm->fetchAll(PDO::FETCH_ASSOC));

Just FOUR lines

Upvotes: 1

Related Questions