I created an API for the Java desktop application because I want to get the data from an online database. The beginning was fine. But some parts were not shown as required. Below is how the data is in the database.
patient_id patient_name patient_nic patient_dob patient_note
PTT00001 Rebecca J Burns 988249675V 1998-12-17 Had previously taken medicine for...
PTT00002 Erica L Prom 926715648V 1992-06-21 To show up a second time for...
The PHP code I used to get this as JSON is as follows and it doesn't show any output(A blank page appeared)
PHP Code :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_name'] = $row ['patient_name'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
But when the patient_name is removed using the same code, everything except it appears as below. What is the reason for that?
PHP code 2 :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
Output for PHP code 02 :
[
{
"patient_id": "PTT00001",
"patient_nic": "988249675V",
"patient_dob": "1998-12-17",
"patient_note": "Had previously taken medicine for fever and still not cured. The body is lifeless."
},
{
"patient_id": "PTT00002",
"patient_nic": "926715648V",
"patient_dob": "1992-06-21",
"patient_note": "To show up a second time for heart disease. She is ready for surgery"
}
]
I also need to get the patient_name
Probably in one of the patient "name" there is some invalid char, in this case json_encode() simply return false, add JSON_THROW_ON_ERROR so the execution stop throwing an error.
echo json_encode($response, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
Probably, adding also JSON_INVALID_UTF8_IGNORE will solve the problem.
Anyway, it is worth to find the offending row.
Related
The connection to the database is successful (it's on a server, not local), the query works fine (I echo the name, street works fine), BUT it never echoes the json string back to me.
I tried several tutorials from Google how to convert mysql to json but I never get a result out of it. No errors either.
<?php
include "dbconnect.php";
$sql = "SELECT * FROM Test ";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
echo "<br>";
echo $row["name"];
echo $row["street"];
echo $row["farbe"];
}
echo json_encode($json_array);
?>
I have a php script which should echo a bunch of datasets in a json encoded string. Though the page is blank.
<?php
$con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE");
if(!$sql = "SELECT news.title, news.content, login.username, news.id, news.date, news.timestamp, news.importance, news.version FROM news INNER JOIN login ON news.id = login.id ORDER BY timestamp DESC") {
echo "FAIL";
}
mysqli_query($con,$sql);
$res = mysqli_query($con,$sql);
$result = array();
while($row = $res->fetch_array())
{
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(["result"=>$result]);
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
What is the problem here? I tried some error detection with if(!..) but it did not help. I think the problem may be the array creation and/or echo, though I cannot figure out how to fix that.
You should check the result of json_encode, since you are encoding data that comes from the database you might have some stuff that requires escaping.
$json = json_encode(...);
if ($json === false) {
echo "Error = " . json_last_error() . " " . json_last_error_msg();
// You may want to var_dump the $result var here to figure out what the problem is
} else {
echo $json; // Should be ok
}
So, I put my php page to connect to my android app on a hosted server (Hostgator). Now my PHP script for the JSON data seems to not be returning properly.This was working on my wamp server just fine. Example below of issue...
["data","pre database"][{"email":"thomas#wiregrass.edu","password":"test","fname":"Thomas","lname":"Cummings","phone":"5052030822","temppass":"15151","alert":"B"}]
Any ides as to what I did wrong or what is going on would be appreciated.
PHP script (might be outdated, this project is old):
<?php
$user = "ab73953_test";
$pass = "H3#ther78";
$db = "ab73953_testdb";
$out = array('data', 'pre database');
echo json_encode($out);
$db = mysqli_connect('localhost', $user, $pass, $db) or die("did not work");
$email=$_POST['username'];
$email = "thomas#wiregrass.edu"; // testing
$qry = 'SELECT * FROM users WHERE email = "'. $email .'"' ;
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
$output = array();
if($count > 0){
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
echo json_encode($output);
}
else
echo json_encode("Could not find user");
mysqli_close($db);
?>
That's not valid JSON. JSON is basically javascript: If the json you generate would be a javascript syntax error, then it's not valid json.
You have two separate echo json_encode(...) blocks, so you're producing two entirely separate/distinct json strings. Your output can only be one SINGLE json string.
e.g. [...][...] is two separate arrays that have gotten glued together. It's a javascript syntax error, therefore it's also invalid json. If you had something like
$arr1 = array(...);
$arr2 = array(...);
echo json_encode(array($arr1, $arr2));
you'd end up with
[[...],[...]]
and be ok
But you have
echo json_encode($arr1);
echo json_encode($arr2);
and end up with
[...][...]
which is an outright syntax error.
And note that you're vulnerable to sql injection attacks.
I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author
Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?
If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.
If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.
Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title
If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];
Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}
Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>
Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.