0

I have already used mysql queries with an IN() clause but now I have a problem. So, I have a database with users and I want to search for those who is in the $namesarr array. Unfortunately it does not work. I checked it many times, searched for errors but nothing. It does not give back any rows (num_rows = 0).

Code:

// Get names
$incommnames = "";
$namesarr_ = join("','", $incomm); // join each item with a comma
$namesarr = str_replace("'", "", $namesarr_); // remove any single quotes
$sql = "SELECT username FROM users WHERE username IN (?)"; // but query does not work
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$namesarr);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $uname = $row["username"];
    $incommnames .= '<a href="user.php?u='.$uname.'">'.$uname.'</a>';
}

$stmt->close();

However if I echo the $namesarr_ I get a string like username1,username2 ... so it would work fine but it doesn't. And if I only have one row affected I have no problems. So, what is wrong?

Edit:

$incomm = array_intersect($myf, $theirf);

$myf is the my friends array and $theirf is the their friends array. $incomm is the part in common.

squancy
  • 565
  • 1
  • 7
  • 25
  • `$incomm`? didn't you mean `$incommnames`? – Funk Forty Niner Nov 10 '17 at 22:08
  • Sorry, I missed some code by chance. Just a minute. – squancy Nov 10 '17 at 22:09
  • And how could I make that? I don't really understand your answer and I have already used this method but here I have a problem. – squancy Nov 10 '17 at 22:13
  • `SELECT username FROM users WHERE username IN (username1,username2)` would be invalid. Where as `SELECT username FROM users WHERE username IN ('username1,username2')` would look for 1 user named `username1,username2`. – chris85 Nov 10 '17 at 22:13
  • You need a placeholder for every value in `$incomm`. You then need to bind each value. e.g. if 2 values `SELECT username FROM users WHERE username IN (?, ?)` then you need to bind the 2 values. This will show you how mysqli makes something things more cumbersome than needed. – chris85 Nov 10 '17 at 22:14
  • Oh... but I want to make it dynamic so I don't know how many `?` marks do I need. – squancy Nov 10 '17 at 22:16
  • You'll need to count the number of terms in the array. – chris85 Nov 10 '17 at 22:22
  • And what if I make every item of an array in single quote? For instance `'username1'`,`'username2'` ... – squancy Nov 10 '17 at 22:30

0 Answers0