Json encode displays numbers instead of letters - php

Please help, I tried everything. I getting data from my database that is utf8_bin and displaying in php, but when i put characters like ć,č,ž,š Json displays numbers instead.I already tried mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER_SET 'utf8'"); but nothing. my Json code is :
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
$sviArray = array();
$responseZagreb=array();
// include db connect class
require_once('DB_connect.php');
// connecting to db
$db = new DB_connect();
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER_SET 'utf8'");
// get all products from products table
$result = mysql_query("SELECT *FROM Istra") or die(mysql_error());
$resultZagreb = mysql_query("SELECT *FROM Zagreb") or die(mysql_error());
$place=array();
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["Istra"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["ID"];
$product["datum"] = $row["DATUM"];
$product["grad"] = $row["GRAD"];
$product["place"] = $row["PLACE"];
$product["adresa"] = $row["ADRESA"];
$product["Dogadaj"]=$row["DOGADAJ"];
$product["Cijena"]=$row["CIJENA"];
$product["Slika"]=$row["SLIKA"];
$product["Tip"]=$row["TIP"];
$place=$row['PLACE'];
$result0 = mysql_query("SELECT SUM(ocjena) AS value_sum FROM Ocjena where place='$place'");
$cijena=mysql_query("SELECT SUM(cijena) AS values_cijena FROM Ocjena where place='$place'");
$cijenacount=mysql_query("SELECT COUNT(cijena) AS cijena_count FROM Ocjena where place='$place'");
$result1=mysql_query("SELECT COUNT(ocjena) AS value_sum1 FROM Ocjena where place='$place'");
$row0 = mysql_fetch_assoc($result0);
$row1 = mysql_fetch_assoc($result1);
$row2=mysql_fetch_assoc($cijena);
$row3=mysql_fetch_assoc($cijenacount);
$sum0 = $row0['value_sum'];
$sum1 = $row1['value_sum1'];
$sum2=$row2['values_cijena'];
$sum3=$row3['cijena_count'];
if($sum1!=0){
$rez=$sum0/$sum1;
}
else $rez=0;
$product["Ocjena"]=$rez;
if($sum2!=0){
$rezCijena=$sum2/$sum3;
}
else $rezCijena=0;
$product["cijena"]=$rezCijena;
// push single product into final response array
array_push($response["Istra"], $product);
}
// success
$response["success"] = 1;
$responseZagreb["Zagreb"] = array();
while ($row1 = mysql_fetch_array($resultZagreb))
{
// temp user array
$productZagreb = array();
$productZagreb["id"] = $row1["ID"];
$productZagreb["datum"] = $row1["DATUM"];
$productZagreb["grad"] = $row1["GRAD"];
$productZagreb["place"] = $row1["PLACE"];
$productZagreb["adresa"] = $row1["ADRESA"];
$productZagreb["Dogadaj"]=$row1["DOGADAJ"];
$productZagreb["Cijena"]=$row1["CIJENA"];
$productZagreb["Slika"]=$row1["SLIKA"];
$productZagreb["Tip"]=$row["TIP"];
$place=$row['PLACE'];
$result0 = mysql_query("SELECT SUM(ocjena) AS value_sum FROM Ocjena where place='$place'");
$result1=mysql_query("SELECT COUNT(ocjena) AS value_sum1 FROM Ocjena where place='$place'");
$row0 = mysql_fetch_assoc($result0);
$row1 = mysql_fetch_assoc($result1);
$sum0 = $row0['value_sum'];
$sum1 = $row1['value_sum1'];
if($sum1!=0){
$rez=$sum0/$sum1;
}
$productZagreb["Ocjena"]=$rez;
// push single product into final response array
array_push($responseZagreb["Zagreb"], $productZagreb);
}
// looping through all results
// products node
$sviArray=array_merge($responseZagreb,$response);
// echoing JSON response
echo stripcslashes(json_encode ($sviArray));
}
else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
}
?>

Try to use JSON_UNESCAPED_UNICODE option.
echo stripcslashes(json_encode ($sviArray, JSON_UNESCAPED_UNICODE));

Related

Identify JSON object from different table

I am trying to get data from three different tables (MySQL) using php script in xcode.
I know how to fetch elements from one table but I don't know how I can extend this method to be able to get the data from two other tables using the same php script and NSURLSession in xcode.
My php script for one table (working):
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno(). ') ' . mysqli_connect_error());
}
$sql = "SELECT * FROM table1";
$test = $mysqli->query($sql);
$Nrows = $test->num_rows;
$resultArray = array();
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
else {
echo 'oups.';
}
Now the problem is that I would like to do the same with two others tables. I tried to incorporate my fetching method in a separate php file (say getElementFunction.php) and calling this method in the main file:
getElementFunction.php
<?php
function getElements()
{
$test = $mysqli->query($sql);
$Nrows = $test->num_rows;
$resultArray = array();
if ($result = mysqli_query($mysqli, $sql)) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
else {
echo 'oups.';
}
}
?>
main_file.php:
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno(). ') ' . mysqli_connect_error());
}
include 'getElementFunction.php';
$sql = "SELECT * FROM table1";
getElements() // --> how can I flag the json object as being returned from table 1
$sql = "SELECT * FROM table2";
getElements() // --> how can I flag the json object as being returned from table 2
$sql = "SELECT * FROM table3";
getElements() // --> how can I flag the json object as being returned from table 3
But I don't know if it is correct and how I could "flag" the different json objects that will be returned in order to be used in my xcode script. I would like to run the fetching process in one loop with only one URL.
Just in case, my objective-C script where I need a way to specify from which table is the json object returned...
XCODE script with NSURLSession:
id jsonObject = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSArray *deserializedArray = (NSArray *)jsonObject;
if (deserializedArray.count > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
...
}
If someone could help me...
Thanks!
Not sure to clearly understand.. But you can try a foreach in getElements().
I mean :
function getElements(array $allSQL)
{
//Final array to json_encode
$finalResultsArray = array();
foreach($allSQL as $tableName => $sqlStatement) {
$arrayResults = array();
$test = $mysqli->query($sqlStatement);
$Nrows = $test->num_rows;
if ($result = mysqli_query($mysqli, $sqlStatement)) {
while ($row = $result->fetch_assoc()) {
$arrayResults[] = $row;
}
//echo json_encode($arrayResults);
$finalResultsArray[$tableName] = $arrayResults;
}
else {
echo 'oups.';
}
}
echo json_encode($finalResultsArray);
}
And this part :
$sql = "SELECT * FROM table1";
getElements() // --> how can I flag the json object as being returned from table 1
$sql = "SELECT * FROM table2";
getElements() // --> how can I flag the json object as being returned from table 2
$sql = "SELECT * FROM table3";
getElements() // --> how can I flag the json object as being returned from table 3
Become this :
$sql1 = "SELECT * FROM table1";
$sql2 = "SELECT * FROM table2";
$sql3 = "SELECT * FROM table3";
getElements(["table1"=> $sql1, "table2" => $sql2, "table3" => $sql3]);

PHP | MySql: mysql query concat in where clause

How can I concatenate two columns in where clause
this is my normal query:
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
I want the stud_fname and stud_lname to be concatenated.
here is my full code:
<?php
error_reporting(0);
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("dbmobile_class_record") or die("Could not select database");
// array for JSON response
$response = array();
$instructor_id=$_GET['instructor_id'];
$description=$_GET['description'];
$stud_fname=$_GET['stud_fname'];
$stud_lname=$_GET['stud_lname'];
// get all items from myorder table
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["student"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$student = array();
$student["stud_id"] = $row["stud_id"];
// push ordered items into response array
array_push($response["student"], $student);
}
// success
$response["success"] = 1;
}
else {
// order is empty
$response["success"] = 0;
$response["message"] = "No Records Found";
}
// echoing JSON response
echo json_encode($response);
?>
$instructor_id = $_GET['instructor_id'];
$description = $_GET['description'];
$fullname = $_GET['fullname'];
// get all items from myorder table
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND CONCAT(stud_fname, ' ', stud_lname) = '$fullname'") or die(mysql_error());
Use this one
$result = mysql_query("SELECT stud_id, CONCAT_WS('', stud_fname, stud_lname) AS stud_fullname FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
stud_fullname should contain what you want.

MySQL query returns null results when used in php

I am getting null results when I use the following Like query in PHP Script
$MasjidName = $_GET['MasjidName'];
$Percent = "%";
$search = $Percent.$MasjidName.$Percent;
echo $search;
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '".$search."'";
// get a product from products table
$result = mysql_query($sql) or die(mysql_error());
I have tried the following too
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
The following is the null result I have been getting
{"masjids":[{"MasjidName":null,"Address":null,"Latitude":null,"Longitude":null}],"success":1,"masjid":[]}
whole code added below the following is the script i have been trying to get work
<?php
$response = array();
require_once dirname(__FILE__ ). '/db_connect.php';;
$db = new DB_CONNECT();
if (isset($_GET["MasjidName"]))
{
$MasjidName = $_GET['MasjidName'];
$MasjidName = mysql_real_escape_string($MasjidName); // you have to escape your variable here.
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%$MasjidName%'";
$result = mysql_query($sql) or die(mysql_error());
$response["masjids"] = array();
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$row = mysql_fetch_array($result);
$masjid = array();
$masjid["MasjidName"] = $row["MasjidName"];
$masjid["Address"] = $row["Address"];
$masjid["Latitude"] = $row["Latitude"];
$masjid["Longitude"] = $row["Longitude"];
// success
$response["success"] = 1;
// user node
$response["masjid"] = array();
array_push($response["masjids"], $masjid);
}
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Try this:
$MasjidName = $_GET['MasjidName'];
$MasjidName = mysql_real_escape_string($MasjidName); // you have to escape your variable here.
$sql = "SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%$MasjidName%'";
$result = mysql_query($sql) or die(mysql_error());
Try using
$sql = "SELECT * FROM MasjidMaster WHERE MasjidName LIKE '".$search."'";
I tried SELECT * FROM Customers WHERE City LIKE 's%'; and it gave me perfectly fine result. But when i tried SELECT * FROM 'Customers' WHERE 'City' LIKE 's%'; it gave me a null result.
Just remove '' and give it a try. Hope it helps.

MySQL like Query fails in PHP

$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die mysql_error();
The error i get is
Parse error: syntax error, unexpected T_STRING in /home/maximtec/public_html/masjid_folder/MasjidFinderScripts/find_by_name.php on line 24
This query does work when i use it in MySQL but it doesn't when I place it in a PHP Script
Please suggest a solution
------------EDIT :After changing query from the received answers-------------------------------------
Well I updated my query but now I am getting null results
{"masjids":[{"MasjidName":null,"Address":null,"Latitude":null,"Longitude":null}],"success":1,"masjid":[]}
Following is my full script :
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
//require_once __DIR__ . '/db_connect.php';
require_once dirname(__FILE__ ). '/db_connect.php';;
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["MasjidName"])) {
$MasjidName = $_GET['MasjidName'];
// get a product from products table
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
$response["masjids"] = array();
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$row = mysql_fetch_array($result);
$masjid = array();
$masjid["MasjidName"] = $row["MasjidName"];
$masjid["Address"] = $row["Address"];
$masjid["Latitude"] = $row["Latitude"];
$masjid["Longitude"] = $row["Longitude"];
// success
$response["success"] = 1;
// user node
$response["masjid"] = array();
array_push($response["masjids"], $masjid);
// array_push($response["masjid"], $masjid);
}
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
$result = mysql_query("SELECT * FROM `MasjidMaster` WHERE `MasjidName` LIKE '%moh%'") or die(mysql_error());
A little more tweaking, for good practice wrap table names and table columns in ``.
You also shouldn't need () around ('%moh%')
Try this-
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE ('%moh%')") or die(mysql_error());
You forget parentheses with die(mysql_error())
try this:
$result = mysql_query("SELECT * FROM MasjidMaster WHERE MasjidName LIKE '%moh%' ") or die(mysql_error());
use die() like this die(mysql_error()) .

SQL query in php file error

I have this code passing a variable from a url. When i use $_GET method it returns me a json with no products found but when i give manually the the value that $user_email has from the url it returns me the correct json! what is wrong and how can i correct it? thank you
URL: http://***********/android_connect/get_all_products.php?user_email=m
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
$user_email= $_GET['user_email'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$test= "SELECT *FROM products WHERE user_email= '" .$user_email. "'";
//echo $test;
$result = mysql_query($test) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["firstname"] = $row["firstname"];
$product["lastname"] = $row["lastname"];
$product["email"] = $row["email"];
$product["phone"] = $row["phone"];
$product["address"] = $row["address"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
$product["user_email"] = $row["user_email"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
Try this:
$test= "SELECT * FROM products WHERE user_email = '$user_email'";
EDIT:
$test= "SELECT * FROM products WHERE user_email = $user_email";

Categories