0

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?

1 Answer 1

1
 $STH = $DBH->prepare("SELECT x1 data1, x2 data2 FROM Table1 WHERE x1 = ?");
 $STH->execute([$variable1]);
 echo json_encode($STH->fetchAll(PDO::FETCH_ASSOC));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.