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);
Related
I am trying to make a basic forum, and I am having trouble printing just one row in SQL. Here is my PHP:
<?php
ob_start();
$host = "localhost";
$user = "root";
$pass = "MYPASSWORD";
$db = "MYDB";
$conn = mysqli_connect($host, $user, $pass, $db) or die("cannot connect to database.");
$sql = "SELECT * FROM forum WHERE fid = '{$fid}' JOIN user ON forum.creator=user.id;";
$result = mysqli_query($conn, $sql);
if ($result == true) {
while ($row = mysqli_fetch_assoc($result)) {
print "<h1>{$title}</h1>";
}
}
else {
print "failed to reach post.";
}
ob_flush();
?>
To help out, I believe everything works except for $sql. I have enabled ini_set('display_errors',1); but I am getting no error messages (excpet for my own that I made for the else statement).
Try this query
SELECT * FROM forum JOIN user ON forum.creator=user.id WHERE fid = '{$fid}' ;
I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {
I'm using PHP code to upload or insert data from MDB file to MySQL database.I want my table value get inserted into MySQL database. But data does not inserted into MySQL database.This code shows me no error.Here is my code. please help I have tried every solution on net.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'payroll_system';
//mysql
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$sql = "SELECT * FROM attendance";
$result = mysql_query($sql);
//mdb
$conn2 = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn2->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=C:\\xampp\\htdocs\\payroll\\eTimeTrackLite1.mdb");
$rs = $conn2->Execute("SELECT * FROM AttendanceLogs");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$column1=$row["AttendanceLogId"];$column2=$row["AttendanceDate"];$column3=$row["EmployeeId"];$column4=$row["InTime"];
$column6=$row["OutTime"];$column8=$row["Duration"];
echo "hello";
echo $column1;echo $column2;echo $column3;echo $column4;
$rs->MoveFirst();
while (!$rs->EOF)
{
$attendance_id = $rs->Fields("AttendanceLogId");
$attendance_date = $rs->Fields("AttendanceDate");
$emp_id = $rs->Fields("EmployeeId");
$in_time = $rs->Fields("InTime");
$out_time = $rs->Fields("OutTime");
$duration = $rs->Fields("Duration");
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '"); ?>
<?php
$rs->MoveNext();
}
}
?>
</table> <?php
mysql_free_result($result);
$rs->Close();
$conn2->Close();
$rs = null;
$conn2 = null;
?>
you need to INSERT each records data instead of UPDATE. Re-write the following line:
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '");
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
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);