Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
CREATE TABLE somewhere (
id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (id)
);
INSERT INTO somewhere(id, name) VALUES
(1, 'Chad'),
(4, 'Ned'),
(5, 'Dave'),
(14, 'Newt'),
(18, 'Bill'),
(21, 'Norton'),
(25, 'Alan');
<?php
// $mysqli is already declared as a working database connection by this sandbox
$ids = [1, 5, 18, 25, 34, 56];
$count = count($ids);
$sql = 'SELECT name FROM somewhere';
$orderBy = 'ORDER BY name';
if ($count) {
$placeholders = implode(',', array_fill(0, $count, '?'));
$stmt = $mysqli->prepare("$sql WHERE id IN ($placeholders) $orderBy");
$stmt->bind_param(str_repeat('i', $count), ...$ids);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $mysqli->query("$sql $orderBy"); // a prepared statement is unnecessary
}
foreach ($result as $row) {
echo "<div>{$row['name']}</div>\n";
}