JSON_ENCODE encoding contents of included php file - php

Having a weird issue with JSON_ENCODE. I am using php to retrieve data from a database and JSON to pass it to Javascript. It was working perfectly until I included another php file that I intend to use to do some processing on the data before it is returned. After including the file JSON started encoding both the data returned and the contents of the file that I included.
php code:
<?php
include("GeoLocation.php");//STATEMENT CAUSING JSON TO ACT WEIRDLY
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "go_with_your_mood";
//$lat=(isset($_GET['lat']))?$_GET['lat']:'';
//$long=(isset($_GET['long']))?$_GET['long']:'';
//$geo = new GeoLocation();
$mysqli = new mysqli('127.0.0.1', $dbuser, $dbpass, $dbname);
//Select Database
//mysql_select_db($dbname) or die(mysql_error());
//build query
$query = "SELECT * FROM service where service_type = 'security' limit 5";
//Execute query
$qry_result = $mysqli->query($query);
//initial array to encapsulate each individual row
$jsonArray = array();
// Insert a new array for each row returned
while($row = $qry_result->fetch_assoc()){
$rowArray = array($row["id"],$row["name"],$row["address"],$row["suburb"],$row["postcode"],$row["phone"],$row["latitude"],$row["longitude"],$row["description"],$row["service_type"]);
array_push($jsonArray, $rowArray);
}
echo json_encode($jsonArray);
?>
data that is returned from this file:
Data that should be returned:
336,TERANG PUBLIC HOSPITAL,13 AUSTIN AVENUE,TERANG,3264,,-38.23939895629883000000,142.90240478515625000000,,medical,
337,ALFRED PUBLIC HOSPITAL,55 COMMERCIAL ROAD,MELBOURNE,3004,,-37.84560012817383000000,144.98210144042970000000,,medical,
338,CAULFIELD PUBLIC HOSPITAL,260 KOOYONG ROAD,CAULFIELD,3162,,-37.88240051269531000000,145.01669311523438000000,,medical,339,NORTHERN PUBLIC HOSPITAL,185 COOPER STREET,EPPING,3076,,-37.65259933471680000000,145.01510620117188000000,,medical,340,MAFFRA PUBLIC HOSPITAL,42-48 KENT STREET,MAFFRA,3860,,-37.96120071411133000000,146.98339843750000000000,,medical
Does anyone know why JSON is returning the contents of the included file as well as my data?

Seems like short tags <? are disabled. And looks like your geolocation.php file starts with <? instead of <?php
Either edit your geolocation.php file and replace <? with <?php in the start.
Or include it like following
include( 'GeoLocation.php' );
Meaning include it by putting space before and after or copy paste the include code at it is written above. Hopefully one of these solutions work.
Alternatively, if you can then enable short tags.

Related

Select hebrew from mysql database

honestly I am coming here after trying everything I could find online in order to fix that problem but nothing worked..
I have a phpmyadmin database table that encoded to utf_general_ci, when I insert data in Hebrew into it it works fine and I can see the Hebrew in the table on PhpMyAdmin, but when I need to retrieve the Hebrew data from the table that's when the problem starts...
right now I am using a simple sql query to select data from the table and I tried every code that should fix it I could find online but nothing seems to work.
my current code is:
<?php
$db = "android";
$username = "root";
$password = "";
$host = "localhost";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1]));
}
$str = json_encode(array($response));
echo $str;
mysqli_close($conn);
?>
and the output of the Hebrew word is \u05d4\u05d9\u05d9 what seems like a different encoding, my php file is encoded to UTF-8 and I am using npp to write it.
please try helping me out on this one cause I couldn't find an answer
This is a json_encode() behaviour, by default Unicode char are escaped as \u...
Try with JSON_UNESCAPED_UNICODE flag :
<?php
echo json_encode($arr, JSON_UNESCAPED_UNICODE);

PHP json_encode is returning local language characters as html entities. Output needed in unicode

My php web service uses json_encode to return json data fetched from MySQL database table. The data should be returned in whatever local language as unicode. Instead local characters like hindi/telugu/bengali are displayed as html entities. But output is needed as unicode and NOT html entities.
<?php
//header('Content-Type: text/html;charset: utf8'); //wasted code line
//Connection and credentials
$servername = "xxx.yyy.zzz.nnn";
$username = "username";
$password = "password";
$dbname = "mydb";
//variables to store fetched data
$item[]=array();
$dataArray[] = array();
// Create connection
$conn = mysql_connect($servername, $username, $password);
//mysql_set_charset('utf8', $conn); //wasted code line
$mytopid = mysql_real_escape_string($_GET['mytopid']); //get input
$query = "SELECT * FROM datamaster where Id > '$mytopid' order by Id desc"; //Now query
//mysql_query("set names 'utf8'"); //wasted code line
if ($result=mysql_query($query,$conn)){
$rows = mysql_numrows($result);
$i= 0;
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//wasted code lines
//$dataArray[$i]["shortid"] = utf8_encode($row['Id']);
//$dataArray[$i]["shorttitle"] = utf8_encode($row['Title']);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
$dataArray[$i]["shorttitle"] = $row['Title'];
$i++;
}
$item[0]["response"] = 1;
$item[1]["matching"] = $rows;
$item[2]["events"]=$dataArray;
echo json_encode($item);
}else{
$item[0]["response"] = 0;
}
//echo json_encode($item, JSON_HEX_TAG| JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); //wasted code line
mysql_close($conn);
?>
Got Output:
Actual Output
Required Output:
[{"shortid":"5","shorttitle":"\u0c38\u0c32\u0c4d\u0c2e\u0c3e\u0c28\u0c4d\u200c \u0c05\u0c21\u0c3f\u0c17\u0c3f\u0c28\u0c3e \u0c05\u0c35\u0c15\u0c3e\u0c36\u0c2e\u0c3f\u0c35\u0c4d\u0c35\u0c32\u0c47\u0c26\u0c41!"}]
I finally convert it at my client program decode to local language.
The required output is supposed to be the default behaviour of json_encode. Despite most trials per php documentation (see the commented CODE lines that show my trials //wasted code line) the output continues to be in html entities except for English language.
My client programming language does not translate html entities.
Is there a php way to get the required output?
I have tried every possible concept on stack overflow and in php documentation. Now I need help.
Please refer to my database language settings
Use json_encode($item, JSON_UNESCAPED_UNICODE);. It will encode multibyte characters literally.
You can get more info here.
Actually it's strange your client side cannot handle escaped characters. What do you use exactly?
Thnak you Wazelin for the prompt reply. I had tried the JSON_UNESCAPED_UNICODE approach too earlier. But that output continued to be html entities.
A temporary fix to the problem I have incidentally tumbled in to using html_entity_decode.
I changed the code lines in while loop to:
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
//handle html entities of local language
$dataArray[$i]["shorttitle"] = html_entity_decode($row['Title']);
$i++;
}
That had given the required output.
But doing this to every single web service is not like an ideal solution.
Quite strangely the default json_encode behaviour is very elusive in my case.
Check documentation:
http://php.net/manual/en/function.json-encode.php
There are some options which allows you to encode your data correctly.

android mysql database returning null only in one field

I'm pulling data from a database using JSON and MySQL in my android app. It successfully pulls the "Title" and "Image_URL" fields from my database. But my "Content" field, which contains large paragraphs of text, returns null. When I type in some short text, it shows up. But when copy/pasting my long paragraphs it returns null.
the "Content" field I'm using in my database is set to "text". I also tried "longtext", and "varchar (2000)". I tried deleting all inverted commas from my paragraphs too, as I read they can cause issues.
Below is my php code. I don't know anything about php as I'm a beginner to all this but use this simple code and it usually works.
Thank you
<?php
$host = "************";
$db = "***********";
$user = "**********";
$pass = "*********";
$con = mysql_connect($host, $user, $pass);
mysql_select_db($db) or die(mysql_error());
$Title=$_REQUEST['Title'];
$result = mysql_query("SELECT * FROM Reviews WHERE Title= '$Title'");
while($row = mysql_fetch_assoc($result) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>

PHP MySQLi query function parsed incorrectly

I'm trying to fetch data from my MySQL database and display it on a simple webpage.
However when i add the PHP code to the .html file it almost looks like the code isn't parsed as PHP.
The code below connects to the db (which works), I enter a query and then fetch the results.
However given the output it almost looks like the -> in $conn->query($query) is enterpreted as ?>
The page resulting from the code below shows these three lines of text:
query($query)) {while ($row = $result->fetch_assoc()) {echo '
'.$row['Title'].'
';>$result->free();}else"fail";}?>
Which is in accordance to the format i want, but obviously not what intended.
However i get the same resulting page from this code when i remove everything from the second line till $conn->.
Which gives me the impression that the code followed by $conn-> isn't read as PHP code at all.
I think it's also important to note that i don't have this problem in a different part of my page, i.e. creating a database connection works fine and code followed by the query is parsed as i would expect.
Is my assumption correct and how can i counter this? Or have a missed something obvious causing this error?
<div class="col-sm-8 blog-main">
<?php
$servername = "localhost";
$username = "root";
$password = "marvin";
$dbname = "blogpostdb";
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT * FROM posts";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
echo '<div class="blog-post">
<h2 class="blog-post-title">'. $row['Title'] .'</h2></div>';
}
$result->free();
}
else{
echo "fail";
}
?>
</div><!-- /.blog-main -->
You need to change the extension from .html to .php.
Files with the .html extension won't parse PHP, unless the webserver is configured to do so.

wrong '.$row["column_name_here"].' encoding

I'm a bit newbi in PHP. I implemented http://www.sanwebe.com/2013/03/loading-more-results-from-database solution in my new website: http://do2go.pl/do2go-nowa/
its working well - except encoding. My DB and all things are in UTF8. When fetch taking data from DB UTF8 seems not working.
Heres configuration and fetch code:
Config:
<?php
$db_username = 'kamio2_do2gonowa';
$db_password = 'JeremiasZ1!';
$db_name = 'kamio2_do2gonowa';
$db_host = 'localhost';
$item_per_page = 2;
mysqli_query ("SET NAMES 'utf8'"); mysqli_set_charset('utf8');
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name) or die('could not connect to database');
?>
And fetch:
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
header('Content-Type: text/html; charset=UTF-8');
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB, "SELECT id,introtext FROM w7wst_content ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'"><span class="page_message">'.$row["introtext"].'</span></li>';
}
echo '</ul>';
?>
I added mysql_query ("SET NAMES 'utf8'"); mysql_set_charset('utf8'); but this does nothing. Still getting � symbols and ? instead of " All next 3 was changed directly in DB tables for html symbols which isn't a solution.
Any help appreciated! :)
(To close the question, since this was the solution to the OP's problem)
Add $connecDB->set_charset("utf8"); just before $results = mysqli_query($connecDB...
You are using mysql and mysqli in one script. Only use mysqli as mysql has been deprecated. That said try this:
mysqli_character_set_name($connectDB);
mysqli_set_char_set($connectDB, 'UTF8');
Set these after your connection script.
Did you check if they are properly stored in the table? Try typing this in your database(not in PHP):
SELECT * FROM w7wst_content;
and see if it's displaying properly. Alternatively you can check table contents with some tool like phpmyadmin. If it's not you have to set collation to something like utf8_general_ci.
EDIT: Also, how about setting the charset AFTER connecting to the database, hm? :)

Categories