Solve New Line in JSON via PHP - php

I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows,
I Get Invalid argument supplied for foreach() Because of New Line in json in Some Rows. How Can I Solve This?
This One is Not Okey
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
AndThis One is Okey
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
And This is My Code:
<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>

Replace your new line with \n before json decode:
$json = preg_replace('/\r|\n/','\n',trim($json));
$jason_array = json_decode($json,true);

The problem is invalid JSON format.
If your text content have multi lines, you should be use \n, not typing a enter.
[{"id":"26","answer":[{"option":"4","text":"Hello\n"}],"type":"3"}]
^^

Related

PHP Script does not echo json encoded 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
}

Parsing Array And Object json Via PHP - Invalid argument supplied

I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows,
Why I Get This Warning for Some Rows? Warning: Invalid argument supplied for foreach() in C:\wamp64\www\json\json.php on line 18
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"3"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"3"}]
And This is My Code:
<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>
That is Strang, Why Some Row Has Output And Some Rows Hasn't Any Output, Those Json Type Are Same.
I Find The Problem, Because Some json entered, I Mean.
This One Has Warning: Invalid argument supplied for foreach()
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
And This One is Okey
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
How Can I Fix The Problem?
you also try is_array before your for each loop
if (is_array($jason_array))
{
foreach ($jason_array as $data) {
{
...
}
}

How do I output the result from an sql query onto the screen in php

The following is the code I use to try and achieve this.
$con=mysqli_connect("localhost:8889","root","root","booksmart_properties");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
echo "we connected";
}
// Perform queries
$sql=mysqli_query($con,"SELECT * FROM ListedProperties");
$result=mysqli_fetch_assoc($sql);
echo $result['*'];
mysqli_close($con);
?>
I'm new to php and i'm sure it's something small, I just can't see it.
Use PHP foreach loop like this:
foreach($result as $key => $val)
{
print $val;
}
You are using
$result = mysqli_fetch_assoc($sql);
which will fetch a result row as an associative array
So you can call your result with a key to get a value.
example:
$result['id']
or to get all:
foreach($result as $key => $value)
{
print $value;
}

JSON returns [null,null] in my app

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

"Array" Appearing Before JSON Ouput

I'm new to PHP and I don't understand why there is an extra word ARRAY infront of the JSON string.
Heres the output of JSON String:
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
This is the PHP file:
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
Remove
echo $response;
which is printing the word Array. If you try to echo the array, it will display the word 'Array' rather than printing the content of an array itself. Use print_r() function to display the content of an array.
print_r($response);
With the exception of classes that use the __to_string magic method, echo and print will only output the string interpretation of a variable's value. Number types (integers and floats), strings, and (I think) booleans have a straightforward string representation. Any other variable (arrays, objects, resources) will either output nothing, their variable type, or throw a fatal error.
For arrays and objects, print_r() will go through each member/property and attempt to convert it to a string (print_r being shorthand for print_recursive). So print_r($response) will give you the full array.
Bear in mind that generally the full array is only useful to output for debugging. Passing a php string version of an array to javascript is likely to be useless.

Categories