0
<?php
try {
   $conn = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $data = $conn->query('SELECT id FROM products');
   foreach($data as $row) {
     $r[] = json_encode($row);
   }
} catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage();} 
?>

<script type="text/javascript">
var jArray = <?php echo json_encode($r); ?>;
function showme(j) {
    for(var i=0; i < j.length; i++){ document.write(j[i]); }
};
showme(jArray);
</script>

results...

{"id":"172","0":"172"}{"id":"173","0":"173"}{"id":"174","0":"174"}...

notice the extra ,"0":"172"

I believe I am getting the error in how I am passing data in the PHP foreach or use of PDO. Honestly I just want the smallest footprint to grab data from MySQL so I can play with JavaScript and the data. Any ideas on getting rid of the extra data (and/or performance improvements on use of PDO)? Please no libraries as I have to (want to) use pure JavaScript and limit the server resources.

1 Answer 1

3

You are getting the results in both numerically indexed and associative format because that's the default PDO fetch mode. This can be changed with PDOStatement::setFetchMode.

For example, setting the fetch mode to PDO::FETCH_ASSOC will remove the 0 keys from your result arrays and leave just id:

$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row) {
    $r[] = json_encode($row);
}
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.