Skip to content

Instantly share code, notes, and snippets.

@shibbirweb
Created September 23, 2018 16:19
Show Gist options
  • Save shibbirweb/3a2ae8f9e0c4a18161018580460a312c to your computer and use it in GitHub Desktop.
Save shibbirweb/3a2ae8f9e0c4a18161018580460a312c to your computer and use it in GitHub Desktop.
[MySqli to JSON] Convert MySqli Database to JSON format by PHP (PDO)
<?php
$database_name = "your_database_name"; //database name
$database_username = "your_database_username"; // database username
$database_user_password = "your_database_user_password"; //database user password
$table_name = "your_table_name"; // your table name
try {
$db = new PDO('mysql:host=localhost;dbname=' . $database_name . ';charset=utf8', $database_username, $database_user_password);
//echo "Connected";
}
catch (PDOException $e) {
//print "Error!: " . $e->getMessage() . "<br/>";
echo "Not Connected";
die();
}
$query = $db->prepare("SELECT * FROM " . $table_name . " ;");
$query->execute();
if ($query->rowCount() > 0) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);
} else {
$json['success'] = 0;
$json['message'] = 'No Data found';
$json['myintro'] = '';
echo json_encode($json);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment