Invalid JSON format from PHP json encode - javascript

I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>

It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}

Related

Decimal Database to JSON

I have Decimal data type in my database with value 0.00 but in JSON result is .00, How I can convert so i can still get 0.00 in result ?
I working in Jquery.. Thanks
This my code
<?php
include "../../../config/config.php";
$kd_entitas=$_POST['kd_entitas'];
$tglAwal = $_POST['tglAwal'];
$tglAkhir = $_POST['tglAkhir'];
$con = sqlsrv_connect(serverNameAST,$connectionInfoAST) or die('Unable to Connect');
if( $con === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
else{
//$sql = "SELECT SELECT #rownum := #rownum + 1 AS urutan, t.* FROM SYS_DEPT t, (SELECT #rownum := 0) r";
$sql="[Daily_report_r] '$kd_entitas','$kd_entitas','$tglAwal','$tglAkhir'";
$result = sqlsrv_query($con, $sql, array(), array( "Scrollable" => 'static' ));
$data = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$data[] = $row;
}
$datax = array('data' => $data);
echo json_encode($datax);
}
?>
Result JSON in field oustand
Result from my database sql server
You have two problems here:
When you're getting the data from database all values will be strings. If you want a specific number to be a double then you have to explicitly cast it to a double.
If you want to preserve zero fraction in json you have to use JSON_PRESERVE_ZERO_FRACTION flag in json_encode. See http://php.net/manual/en/function.json-encode.php for details.
But this solution will preserve only one zero and will only work on numbers of type double. If you want to have more zeros after coma you have to leave the number in the string and handle yourself.
If the number from the database is returned without the fraction part then check your field type or field precision.

Can't json_decode() from file - Syntax error

I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).
According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);
You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);

Receive post with description containing '%' and two letter together

I have problems with treatment of Post. I received a string with the symbol '%' and two letters together, like 'Geci%de', but on PHP the var_dump I receive a different string, like 'Geci�', if try to use utf8_encode and utf8_decode, however the error continued, the strings resulted were 'GeciÞ' and'Geci?'. How is the better way to convert in the orignal string? I need to use in postgreSQL, it will be in select.
It is uses to treatment:
$data = strip_tags($data);
$data = trim($data);
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data;
$data = preg_replace("#(--|\|)#s", "", $data);
$data = urldecode($data); // especific to Ajax
return utf8_decode($data);

How to add items from a foreach loop into a string with json_encode() in PHP?

I'm trying to insert into a string all emails retrieved from the database, so I can use javascript to check if the email typed by the user into a form field is already registered. I'm trying to use json_encode().
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
$arrayEmails = mysqli_fetch_array($resultado);
foreach($arrayEmails as $row){
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
Now, I'm getting this error:
Warning: Illegal string offset 'userEmail' in /home/verificarEmail.php
on line 21
Line 21 is $emails[]=array($row['userEmail']);
What Am I doing wrong?
UPDATE:
I'm also trying:
$resultado = mysqli_query($conectar,$listarCorreos);
$emails = array();
while($row = mysql_fetch_assoc($resultado)) {
$emails[] = $row;
}
echo json_encode($emails);
And I get this error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
object given in /home/verificarEmail.php on line 18
Line 18: while($row = mysql_fetch_assoc($resultado)) {
Use MYSQLI_ASSOC like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado, MYSQLI_ASSOC) ) {
$emails[]=array($row['userEmail']);
}
echo json_encode($emails);
There are a few problems there. To get your emails in an array do:
$resultado = mysqli_query($conectar,$listarCorreos);
if(!resultado) die($mysqli_error($conectar));//check for errors
$emails = mysqli_fetch_all($resultado);//fetch all results
echo json_encode($emails);
That should get your code working or show you the error. However, please don't do this.
so I can use javascript to check if the email typed by the user into a
form field is already registered
This is a terrible idea security wise because it will expose all your users' emails to people who are not even registered to your site. You should instead look up the desired username in the DB directly. If it's not there, then it hasn't been registered before. The Javascript side should only get a available or not available response.
The process (pseudo-code):
SELECT userEmail from usarios WHERE userEmail = ? ? is email to look for
execute query and capture $resultado
If $resultado is false, die(mysqli_error($conectar)) to show error
if mysqli_num_rows($resultado) === 0 email is available; else not available
Echo available or not available to Javascript
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail'];
}
echo json_encode($emails);
use the code like below
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$listarCorreos = " SELECT userEmail
FROM usuarios
";
$resultado = mysqli_query($conectar,$listarCorreos);
while ( $row = mysqli_fetch_array($resultado) ) {
$emails[]=$row['userEmail '];
}
echo json_encode($emails);

saving script variables from php variables in while loop

been trying to save my data from my while loop to script variables but no success. Did an example if how I want to save my php data to script variables. This doesn't work for me. Anyone have any idea? Don't want to save all data manually. Very greatful for answers! Ask if you don't understand :)
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
echo "<script>";
echo "var data" . $id . " = " . $data . ";"; //???
echo "</script>";
}
The best thing to do here would almost certainly be to create an array (on the PHP side), and then output the entire array at once.
Assuming you've built an array in $array, here's how you would output it:
echo "<script>var data = " . json_encode($array) . ";</script>"
More on json_encode in the docs, but basically it encodes the PHP data as valid JSON. Since JSON is a subset of JavaScript object and array initializer syntax, you can safely output JSON text as the right-hand side of an assignment, as above.
In the client-side script, you'd access each item via data[0], data[1], etc. up through data[data.length - 1].
Separately, note what Nathan Loding pointed out in a comment on the question:
...[you're] calling mysql_fetch_array($data) and then [have] $data = $rows['data'] two lines further down, thus overwriting $data...
...which will tend to mess up your fetch loop.
You are duplicating the script tag on every iteration.
you also need to surround the data in double or single quotes.
But it is not so safe..
$id = 0;
$data = "";
$vars = "";
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
$vars .= "var data" . $id . " = \"" . addslashes( $data ). "\";"; //???
}
echo "<script>";
echo $vars;
echo "</script>";
}

Categories

Resources