I am learning about PHP, so I try to do some exercises. Now I wanted to upload an array in JSON format to my script and insert this array into the query. To test it I used three fixed values in the array. The problem I have is that only the result of the first element of the array is returned and not all three. I thought about fetching multiple values wrong, but with a fix condition providing more then one result it does work fine. I also thought maybe the array is passed wrong, but when I printed it from the script I got it returned completely like this:
(
[0] => 141
[1] => 145
[2] => 54
)
Does anyone know where it is thought wrong?
My script:
<?php
include 'DBConfig.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['arrayList'])){
$JSON_Received = $_POST['arrayList'];
$obj = json_decode($JSON_Received, true);
$matches = implode(',', $obj);
$query = "SELECT * FROM TestTable WHERE id IN ('$matches')";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
}
header('Content-Type:Application/json');
echo json_encode($array);
mysqli_close($conn);
?>
D/TAG: Response: [{"id":"145","name":"x"}]. It looks like that's pretty much it, but I don't have an explanation why$query = "SELECT * FROM TestTable WHERE id IN (".implode(',', $obj).")";to avoid one line and if$objlooks like an array like this$obj = array(0=> your_id, 1=> your_id, ...);implode()directly in the query! Do you have any idea why that might cause such a problem?...id IN ('$matches')you will have something that looks like this'141, 145, 54'(a STRING) instead of141, 145, 54(a list of INT). You can try to write...id IN ($matches)to check if it works too :)