Convert php data to Json - php

I'm a newbie to php. I'm working on fetching the result from the DB and to send those details in the format of Json to the ajax call. Whereas I'm not able to convert using json_encode.
I'd like to get the result in the format of
[{"id":1,"name":"Rafael","password":"rafael"},{"id":1,"name":"nadal","password":"nadal"}]
My php code is
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$jsonArray = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT name,password FROM User");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$password = $row{'password'};
$jsonData = json_encode($name,$password);
}
echo "Json:".$jsonData;

Change the code after mysql_query to:
while($row = mysql_fetch_assoc($result))
{
$jsonArray[] = $row;
}
echo json_encode($jsonArray);
Note that you do not select the ID in the query. it should be
$result = mysql_query("SELECT id, name, password FROM User");

The parameters within a json_encode must be an array.
You should use
$jsonData = json_encode( $array ); //$array is your array element

Use Something like this
$queryString = "SELECT * FROM user";
$query = mysql_query($queryString) or die(mysql_error());
$db = array();
while($dbs = mysql_fetch_assoc($query)) {
$db[] = $dbs;
}
echo
$output = json_encode(array(
"success" => mysql_errno() == 0,
"information" => $db
));
myoutput will be look like this;
it will display all the fields in your databasetable
{"success":true,"information":[{"id":"1","username":"sampleName","LastName":"SampleLastName"}]
}
Hope it works :D

Related

how to convert my sql query into json using php?

I have created a text box in which a query is entered and I need to run the query to display the values stored in the mysql table using php. Kindly help me with the approach of the project or any links that can help me. I have tried doing it by taking single query in php:
<?php
$username = "username";
$password = "password";
$host = "localhost";
$database="test";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `date_joined`, `city` FROM `users`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
But I want to get the json for every query that is being entered in the textbox. How do I handle that ?
Try this:
<?php
$username = "username";
$password = "password";
$host = "localhost";
$database="test";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "";
$myquery = $_POST["id_of_the_text_box"];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
But try to validate first the SQL entered in the textfield.

slim framework no output displayed

I'm trying to get a json file using Slim Framework. The code I'm trying is mentioned below
$app->get('/forum/:id', function ($id) {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = "Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'id'";
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
The output displayed on the browser is []
When I try the above code without passing parameter, i.e
$app->get('/faqs/', function () {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'abc#gmail.com'"
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
then it works fine
How do i fix this, I need to get this working to get the json file by passing any email id's from the database
You're forgetting the $ in the parameter, it thinks you're looking for an email address of 'id', not the contents of $id.
SELECT * FROM y123_forum WHERE email = '$id';
Note that this is a horrible, bad, unsafe way to pass parameters to a SQL query. The correct way would be to parameterize your query and execute this way:
$SQL = 'SELECT * FROM y123_forum WHERE email = ?';
$stmt = mysqli_stmt_init($db_handle);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, 's', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
}
The 's' in mysql_stmt_bind_param tells the driver your $id variable should be treated as a string, and escapes it appropriately.

How to JSON encode multiple rows from SQL statement using PHP

I'm in the process of building an iOS app that uses a webservice for data. The webservice consists of PHP, MySQL database.
I've successfully managed to JSON encode the data returned, but the code I am using only seems to encode 1 row.
I wanted to get some advice on how to encode multiple rows?
Thanks.
<?php
$username = "root";
$password = "*******";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//print "Connected to MySQL<br>";
$selected = mysql_select_db("newtest",$dbh)
or die("Could not select first_test");
$query = "SELECT * FROM MyGuests ";
$result=mysql_query($query);
echo json_encode(mysql_fetch_assoc($result));
?>
$query = "SELECT * FROM MyGuests ";
$result=mysql_query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print_r json_encode($rows);

mysql_fetch_array($result) echo $rows in html

So I have these specific rows that I'm pulling if a code matches the database but I have no idea on how to echo this to my full html, is there anyway to make this $rows a $_POST or $_get to html?
thanks
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
} else {
echo "error msg";
}
mysql_close($connection);
?>
You just need to update your while loop
Following code is to create your result Array, by that result array you can use the values in HTML too.
$resArr = array();
while($row = mysql_fetch_array($result)) {
$resArr[] = $row;
}
echo "<pre>";print_R($resArr);exit;
try
$query = "SELECT * FROM '$table' WHERE '$field' = '".$_GET["qcode"]."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_assoc($result))
{
$name1 = $row[$field];
$test1 = $row[$test];
echo "Hello:" .$name1. $test1;
}
}
else { echo "error msg"; }
Also use mysql_real_escape_string() to prevent sql injection or better to use mysqli or PDO
You have two alternatives :
i) Use a .php file and write the html part there. This way you run php code with simple, php tags and display stuff where you need.
example :
Create a file called test.php and put this code in it and run.
</head>
<body>
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "<p>".$name." ".$test."</p>";
}
}
else { echo "error msg"; }
mysql_close($connection);
?>
</body>
</html>
This example puts the content in a paragraph in the html.
ii) echo the content from php by encoding it JSON and receive it using jquery from your html form. I'll not elaborate on this since it is not in the scope of the question.
And DO REMEMBER TO USE THE mysql_real_escape_string() to keep your code robust and prevent sql injection.

How to output a JSONArray from a webservice written in PHP

I have webservice written in PHP that reads from the local database and output the result in JSON.
However, I am unable to output it into a JSONArray.
Here is the php script
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$response=array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select test");
//execute the SQL query and return records
$result = mysql_query("SELECT name, country FROM android");
$response["infos"] = array();
while ($row = mysql_fetch_assoc($result)) {
$info = array();
$info["name"]=$row["name"];
$info["country"]=$row["country"];
print(json_encode($info));
}
//close the connection
mysql_close($dbhandle);
?>
This is the output from the webservice
{"name":"develop","country":"mru"}{"name":"fufu","country":"tutu"} {"name":"chikaka","country":"aceVentura"}
But I have been told that this is not in JSONArray.
What am I missing here?
Thank you
In your example you're echo'ing out multiple JSON strings because your output code is within a while loop. There should only be one output for the JSON string. The code below will give you a two dimensional array in JSON format.
$info = array();
while ($row = mysql_fetch_assoc($result))
{
$arr = array();
$arr["name"] = $row["name"];
$arr["country"] = $row["country"];
$info[] = $arr;
}
echo json_encode($info);

Categories