Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
Accounts
Articles / Notes
Biology
Chemistry
Computer Class
Daily Current Affairs
English
General Knowledge
History
Indian Law
Interview Questions
Mathematics
Muft Shiksha - Free Education
Science

How to convert mysqli result to JSON?

0

I have a mysqli query which I need to format as JSON for a mobile application.

I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die(‘There was a problem connecting to the database’);

$stmt = $mysql->prepare(‘SELECT DISTINCT title FROM sections ORDER BY title ASC’);
$stmt->execute();
$stmt->bind_result($title);

// create xml format
$doc = new DomDocument(‘1.0’);

// create root node
$root = $doc->createElement(‘xml’);
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) :

$occ = $doc->createElement(‘data’);
$occ = $root->appendChild($occ);

$child = $doc->createElement(‘section’);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);

endwhile;

Akbar Khan Posted new comment 5 Apr, 2024

$mysqli = new mysqli(‘localhost’,’user’,’password’,’myDatabaseName’);
$myArray = array();
$result = $mysqli->query(“SELECT * FROM phase1”);
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);

Add a Comment
Join for Teach