First of all, your mock JSON is broken. It contains repeated properties.
If you must use a loop (which you don't have to) you can prepare the statement before the loop and execute within. Then use get_result()
and fetch_all()
to get the data.
mysqli
//mysqli connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('localhost', 'user', 'password', 'db_name');
$conn->set_charset('utf8mb4'); // always set the charset
$jsonobj = '[ "ascaasease", "onetoelevn"]';
//mock json
$obj = json_decode($jsonobj);
$stmt = $conn->prepare('SELECT code, header, body FROM messages WHERE code=?');
$stmt->bind_param('s', $value);
$array_push = [];
foreach ($obj as $key => $value) {
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$array_push = array_merge($array_push, $data);
}
$return = array("resoponse" => array("check" => "check"), "array" => $array_push);
echo json_encode($return);
If you don't have to use a loop, then you can use WHERE IN()
$jsonobj = '[ "ascaasease", "onetoelevn"]';
//mock json
$obj = json_decode($jsonobj);
$wherein = str_repeat(',?', count($obj) - 1);
$stmt = $conn->prepare("SELECT code, header, body FROM messages WHERE code IN(? $wherein )");
$stmt->bind_param(str_repeat('s', count($obj)), ...$obj);
$stmt->execute();
$array_push = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$return = array("resoponse" => array("check" => "check"), "array" => $array_push);
echo json_encode($return);
PDO
Of course, all of this would be simpler if you were using PDO. If it is not too late, can you consider switching over to PDO instead of using mysqli?
Option 1:
// PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
$jsonobj = '[ "ascaasease", "onetoelevn"]';
//mock json
$obj = json_decode($jsonobj);
$stmt = $pdo->prepare('SELECT code, header, body FROM messages WHERE code=?');
$array_push = [];
foreach ($obj as $key => $value) {
$stmt->execute([$value]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$array_push = array_merge($array_push, $data);
}
$return = array("resoponse" => array("check" => "check"), "array" => $array_push);
echo json_encode($return);
Option 2:
$jsonobj = '[ "ascaasease", "onetoelevn"]';
//mock json
$obj = json_decode($jsonobj);
$wherein = str_repeat(',?', count($obj) - 1);
$stmt = $pdo->prepare("SELECT code, header, body FROM messages WHERE code IN(? $wherein )");
$stmt->execute($obj);
$array_push = $stmt->fetchAll(PDO::FETCH_ASSOC);
$return = array("resoponse" => array("check" => "check"), "array" => $array_push);
echo json_encode($return);