0

I have an array of ids $friends = array(0001, 0002, 0003, 0004) and a database where table_name = friends, column_header = fid. fid in friends may or may not contain one of the friend IDs. I want to input $friends into the query, and return all of the present values that were both in $friends and in a row of fid.

I'm sure the fid={array_values($friends)} is wrong, but I don't know how to pass the WHERE portion an array of values...

//All DB_X's are defined in another file that is included in this actual file
$db = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$stmt = $db->prepare("SELECT fid FROM friends WHERE fid={array_values($friends)} ORDER BY fid ASC");
$stmt->execute();

$friendResults = $stmt->fetchAll();

1 Answer 1

1

You will need to make use of SQL's IN operator:

SELECT ... FROM ... WHERE foo IN (val1, val2, ...)

You can use PHP's implode() function to get the desired SQL bit:

$values = implode(', ', array_values($friends));
$query = "SELECT ... FROM ... WHERE fid IN ({$values})";

The above will work if your values are numeric. If they are strings, you'll have to modify the values before implode()ing:

$values = array_map(array_values($friends), function($value) {
    return "'{$value}'"; // Here is where you could do sanitization
});
$values = implode(', ', $values);

PLEASE NOTE: You must properly sanitize the data in $friends to prevent SQL injection.

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

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.