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
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.
I'm just trying to get data from a table in a MySQL database, but outputting the result after running mysqli_fetch_all($result, MYSQLI_ASSOC); returns {"current_field":null, "field_count":null, "lengths":null, "num_rows":null, "type":null}. I haven't had a problem with this before, as I was getting correct data back before. Other queries that would return true like INSERT and UPDATE work fine, and there are records in the table. I am, however, pretty new to PHP, so I could be missing something obvious.
<?php
include("APIBase.php");
//Get query from POST request
//$content = trim(file_get_contents("php://input"));
//$decoded = json_decode($content, true);
//$query = $decoded["apiData"];
if($_SERVER["REQUEST_METHOD"] == "GET"){
//exit("yeahhhh no");
$query = "SELECT * FROM `user_accounts`"; //this line for testing purposes
}
//connect to database
$conn = mysqli_connect("localhost", "id14495771_root", "Thereisnopa55word$", "id14495771_user_info");
$result = mysqli_query($conn, mysqli_escape_string($conn, $query));
//check result
if($result == false){
exit(APIResponse(true, mysqli_error($conn), array()));
}
else if($result == true){
$data = $result;
}
else {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
//free and close connection
mysqli_free_result($result);
mysqli_close($conn);
//return data
$output = APIResponse(false, "", $data);
exit($output);
?>
APIBase.php:
<?php
header("Access-Control-Allow-Origin: *");
function APIResponse(bool $isError, $errorMessage = "", $data){
$output = array("isError" => $isError, "errorMessage" => $errorMessage, "data" => $data);
exit(json_encode($output));
}
?>
Do a strict comparison for the if else statement.
In my else if statements, I was using == instead of ===. So after type-juggling, $result==true came back as true. To fix this, just replace == with === to check type as well.
if you got a results or not.. this condition
( $result == true )
will be always your case.
the result variables there is some property and methods belong to A class Php Doc
If you assign the address of the result to the data it will be lost after free result and closing the connection.
the best ways is loop through result using fetch and fill an array or an object dynamically.
the you free the result.
Or maybe you have to clone the result not just assign it as any other variables try it maybe it works.
i m trying to build a JSON array from mysql. it does not get the information from mysql
<?php
$host="localhost";
$pwd="";
$user="root";
$db="mydb";
$con=mysqli_connect($host,$user,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo"failded to connect";
}
$query = mysqli_query($con,"select * from product");
if ($query)
{
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
Notice: Array to string conversion in C:\wamp\www\new\count.php on line 19
What does this error mean and how do I fix it?
Please initialize $flag something like this $flag = array()
hope it was helpful to you.
change print to print_r(json_encode($flag)) you won't get any error
You are converting your array to a json array so you have to use var_dump or print_r().
Sorry for my English. I'm trying to output the data to a database format json. It seems to do everything right, but it is not true outputs. Here is my link which is obtained: http://ksupulse.tk/get_all.php if I did check the validity of the site http://jsonlint.com/ or http://jsonformatter.curiousconcept.com/ get an error.
get_all.php
<?php
header('Content-Type: application/json; charset=utf-8');
?>
<?php
$response = array();
require 'db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT * FROM demo") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["demo"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
$product["detaly"] = $row["detaly"];
array_push($response["demo"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
?>
I've honestly spent so much time searching for this problem, but the answer is not found. All the same, why do I have prints to the database is not json? DB encoded utf_unicode_ci, and the table in utf8_general_ci
There is an extraneous carriage return in front of your { } sequence (which is valid, in itself).
You should not close ?> and then reopen <?php your script after the header instruction.
It outputs garbage to the browser. You really want your stream to begin with the { first character.
In other words (for #KnightRider) the lines 5-7 of the script should be removed!
05 ?>
06
07 <?php
Sorry for answering this is because I could not attempt but have to write my views
Hi, I have checked this which you posted in the comment and JSONlint verifies it as a valid JSON
{"demo":[{"id":"3","name":"123123","detaly":"123123123"},{"id":"4","name":"4444","detaly":"555555"}],"success":1}
What else do you need?
I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it