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);
Related
I'm trying to fetch data from the database but I am getting this error.
Fatal error: Uncaught Error: Call to undefined function
mysql_select_db() in E:\xamp\htdocs\PoliceApp\News\fetch.php:10 Stack
trace: #0 {main} thrown in E:\xamp\htdocs\PoliceApp\News\fetch.php on
line 10
How can I make this right?
<?php
$username="root";
$password="namungoona";
$hostname = "localhost";
//connection string with database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "";
// connect with database
$selected = mysql_select_db("police",$dbhandle)
or die("Could not select examples");
//query fire
$result = mysql_query("select * from News;");
$json_response = array();
// fetch data in array format
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// Fetch data of Fname Column and store in array of row_array
$row_array['Headlines'] = $row['Headlines'];
$row_array['Details'] = $row['Details'];
$row_array['NewsPhoto'] = $row['NewsPhoto'];
//push the values in the array
array_push($json_response,$row_array);
}
//
echo json_encode($json_response);
?>
It should be mysqli_select_db($dbhandle, "police") and other mysql_* functions should be changed to their mysqli_* as well.
<?php
$username = "root";
$password = "namungoona";
$hostname = "localhost";
// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connection string with database
$dbhandle = mysqli_connect($hostname, $username, $password);
// connect with database
$selected = mysqli_select_db($dbhandle, "police");
// query fire
$result = mysqli_query($dbhandle, "select * from News;");
$json_response = array();
// fetch data in array format
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Fetch data of Fname Column and store in array of row_array
$row_array['Headlines'] = $row['Headlines'];
$row_array['Details'] = $row['Details'];
$row_array['NewsPhoto'] = $row['NewsPhoto'];
//push the values in the array
array_push($json_response, $row_array);
}
echo json_encode($json_response);
The code I am working on queries a database through php and then placed the results into an array called CS. This array is then encoded so it can work with javascript. It is then supposed to edit the output so there is a newline after every row. The latter is where I have the problem. I get implode: invalid arguments passed every time regardless of how I edit the implode function.
Here is the code:
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
// encodes php array so it can be used in javascript
$json_array = json_encode($CS);
$conn->close();
// fills Computer_Science.js with the contents of the json_array and adds new lines in between
$json_array_lines = implode($json_array, "/n"); --> this line
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_array_lines, TRUE));
fclose($fp);
?>
I'm at a loss on how to fix the error. Any help given will be appreciated.
I fixed it!
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
$conn->close();
//encode the array so it can be used in javascript and use regular expressions to format it.
$json_string = json_encode($CS);
$re = "/.,/";
$subst = "},\r\n"; --> right here!
$json_string = preg_replace($re, $subst, $json_string);
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_string, TRUE));
fclose($fp);
?>
im currently trying to extract a table from my database (articles) and the table article and put it in an array but im not sure weather or not it wokred because i dont know how to print an array. i was following this link.
http://phpscriptarray.com/php-arrays-tutorials-tour/how-to-extract-mysql-database-data-into-php-array-variable.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
// connect to DB
$db_selected = mysqli_select_db('article', $conn);
if (!$db_selected){
die("can't use article : " .mysqli_error());
}
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = mysqli_query($query);
$number = mysql_numrows($result);
$article_array = array();
$x = 0
while($x < $number)
{
$row = mysqli_fetch_array($result);
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
$x++;
}
echo count($article_array);
//echo "hello";
<?
even the echo hello wont work and im not sure if i was supposed to put a name and quantity in:
$artic = $row['name'];
$amount = $row['quantity'];
You are mixing object oriented with procedural style. Your query and loop should look like this:
$query = "SELECT * FROM `articles`";
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
}
http://php.net/manual/en/mysqli.query.php
Also your PHP closing tag is faulty - should be ?> or omitted.
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);
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