JSON encode a MySQL result using PHP

<?php $dbhost = "localhost"; $dbuser = "dbuser"; $dbpass = "dbpass"; $dbname = "dbname"; $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM customer"; $return_arr = array(); if ($result = mysqli_query( $conn, $sql )){ while ($row = mysqli_fetch_assoc($result)) { $row_array['id'] = $row['id']; $row_array['username'] = $row['username']; $row_array['email'] = $row['email']; array_push($return_arr,$row_array); } } mysqli_close($conn); echo json_encode($return_arr); ?>
I needed to pull the results of a MySQL query from an old DB and return them as a json array to be imported into another DB. This was much simpler than doing a ton of MySQL joins to get the data in a more usable format.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.