Reputation: 3
I was reading something on the Internet and many people say that it's recommended to switch to PDO from old mysql (and mysqli) extensions.
I'm new with this PDO, I learned something about it. For my problem I tried to search stackoverflow, Google, etc, but it didn't helped me.
Original script with mysqli :
$data = mysqli_query($con, "SELECT x1, x2, x3, x4 FROM Table1 WHERE x1 = $variable1");
$row = mysqli_fetch_row($data);
$result_data = array(
'data1' => $row[0],
'data2' => $row[1]
);
echo json_encode($result_data);
This code outputs something like this :
{"data1", 1, "data2", 2}
I tried to change it with this PDO code :
$STH = $DBH->prepare("SELECT x1, x2, x3, x4 FROM Table1 WHERE x1 = ?");
$STH->bindParam(1, $variable1);
$STH->execute();
$row = $STH->fetchAll();
$result_data = array(
'data1' => $row[0],
'data2' => $row[1],
);
echo json_encode($result_data);
This back me something very strange like
{"data1", 1, 2, 1, "data2", 1, "data2"}, data1 null, data2 null
It should back like with original mysqli script...
I tried with multiple fetch modes like assoc, num, column, what I was found on Internet, but result was very similar and I always get this error :
Notice:Undefined offset: 1 in
What can be the problem, how to fix it?
Upvotes: 0
Views: 102
Reputation: 157839
$STH = $DBH->prepare("SELECT x1 data1, x2 data2 FROM Table1 WHERE x1 = ?");
$STH->execute([$variable1]);
echo json_encode($STH->fetchAll(PDO::FETCH_ASSOC));
Upvotes: 1