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
}
Related
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.
It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got
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
I want to retrieve data from my SQL database and use it on my HTML page.
I have a php script get_score.php like this:
<?php
$con = mysqli_connect( "localhost", "xxx1", "xxx2", "xxx3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `name`, `score` FROM crossstreet ORDER BY `score` DESC LIMIT 5";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$output = ($row["name"]);
}
mysqli_free_result($result);
echo json_encode($result);
mysqli_close($con);
?>
And then I want to retrieve the data I via JQuery. I have read about the cross-origin issue but the data I retrieve and the html/Jquery are on the same server.
$.get("get_score.php", function( data ) {
console.log(window[data]);
}, "json" );
This returns undefined. If I make it $(data) it returns an object like the one on this screenshot.
Where is my mistake; how can I just get the data from the server to use in html?
You need to make $output an array so you get all the rows.
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row['name'];
}
Then you should echo this:
echo json_encode($output);
And in your jQuery code, you should do console.log(data);
mysqli_free_result($result);
echo json_encode($result);
i think this is the problem.
Try to reverse the order. You are making the result free before using it.
Do like this, instead of the above .
echo json_encode($result);
mysqli_free_result($result);
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.