user9155899
user9155899

Reputation: 19

array in query returns only result of first value

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);
?>

Upvotes: 0

Views: 353

Answers (1)

Micka&#235;l Leger
Micka&#235;l Leger

Reputation: 3440

When you write WHERE id IN ('$matches') the result will be WHERE id IN ('141, 145, 54'), so you have a STRING and id are INTEGER.

Try to replace :

$matches = implode(',', $obj);
$query = "SELECT * FROM TestTable WHERE id IN ('$matches')"; 

By

$matches = implode(',', $obj);
$query = "SELECT * FROM TestTable WHERE id IN ($matches)";

Or

$query = "SELECT * FROM TestTable WHERE id IN (".implode(',', $obj).")";`

This way you will have WHERE id IN (141, 145, 54), a list of INT.

Upvotes: 2

Related Questions