JSON doesnt display letters corectly - php

i have the web page witch contains JSON code with data from database , the code is generated by PHP script ,but JSON instead to display those leters "čšćđž" displays something like "\u0161","\u0111" etc , but i cant figure it out where iam wrong , encoding for tables, databse, document , header is UTF-8
here is a link to page http://dmb.site50.net/application.php?app_access_key=c4ca4238a0b923820dcc509a6f75849b
here is source of PHP script
$APP_URL_ACCESS = $_GET['app_access_key'];
$sql_app = mysql_query("SELECT * FROM app_sys WHERE APP_OW_C='$APP_URL_ACCESS'") or die(mysql_error());
if(mysql_num_rows($sql_app)==1){
while($row = mysql_fetch_array($sql_app)){
$APP_UA_ID = $row['APP_UA_ID'];
$APP_NM = $row['APP_NM'];
$APP_H_DMN = $row['APP_H_DMN'];
$APP_H = $row['APP_H'];
$APP_H_DB_UNM = $row['APP_H_DB_UNM'];
$APP_DB_NM = $row['APP_DB_NM'];
$APP_H_DB_PSW = $row['APP_H_DB_PSW'];
$APP_H_DB_SRV = $row['APP_H_DB_SRV'];
$APP_ACTIVE = $row['APP_ACTIVE'];
$APP_OW_C = $row['APP_OW_C'];
}
$ROW_APP[] = array(
'APP_UA_ID' => $APP_UA_ID,
'APP_PERMISSION' => $APP_ACTIVE,
'APP_KEY' => $APP_OW_C);
$APP_ARRAY[] = $ROW_APP;
($APP_ACTIVE == '1')? $sql_connect_app = mysql_connect($APP_H_DB_SRV, $APP_H_DB_UNM, $APP_H_DB_PSW) && mysql_select_db($APP_DB_NM): $_MSG = "Application Is Not Active";
$sql_news = mysql_query("SELECT * FROM news ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array($sql_news, MYSQL_ASSOC)){
//$display_json['data'] = array(
//'id' => $row['id'],
// 'title' => $row['title'],
// 'story' => $row['story'],
// 'img' => $row['img'],
// 'author' => $row['author'],
//'datetime' => $row['datetime'],
//'shorten_story' => substr($row['story'], 0, 150) . '...'); */
$ROW_APP_DATA[] = $row;
//
}
$sql_news = mysql_query("SELECT * FROM actual ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array($sql_news, MYSQL_ASSOC)){
/*$display_json['data'] = array(
'id' => $row['id'],
'title' => $row['title'],
'story' => $row['story'],
'img' => $row['img'],
'author' => $row['author'],
'datetime' => $row['datetime'],
'shorten_story' => substr($row['story'], 0, 150) . '...'); */
$ROW_APP_THIRDPART[] = $row;
//
}
$JSON_ARRAY_APP['application'] = $ROW_APP;
$JSON_ARRAY_DATA_1['news'] = $ROW_APP_DATA;
$JSON_ARRAY_DATA_2['actual'] = $ROW_APP_THIRDPART;
$JSON_ARRAY_DATA['data'] = array_merge($JSON_ARRAY_DATA_1, $JSON_ARRAY_DATA_2);
$JSON_OUTPUT = array_merge($JSON_ARRAY_APP, $JSON_ARRAY_DATA);
echo json_encode($JSON_OUTPUT);
}else{
exit();
}

That's normal. JSON's spec uses the \uxxxx sequence for extended unicode characters. See http://json.org and search for "unicode".
JSON strings are not normally meant for human consumption, so it doesn't really matter how characters are encoded within it. If your consumer properly supports unicode, you'll get your original accented characters back when you decode the json string back to a native data structure.

Related

PHP repeated results

I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line

Unique code generation using Last Insert Id in Code Igniter?

I need to create a drcode using the last insert id in the prescribed format,
previously I have used cor php to get the code but now in codeigniter am not able to get the code as the previous one. How can i do this? I am providing my controller and model
Controller
public function newdoctor_post() {
$employee_id = $this->post('EMPLOYEE_ID');
$doctorname = $this->post('DOCTOR_NAME');
$mobilenumber = $this->post('DRMOBILE');
$users_data = $this->Rest_user_model->doctor_exists($mobilenumber);
if ($users_data == 1) {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Doctor already registered'];
} else {
$speciality = $this->post('SPECIALITY');
$longitude = $this->post('LONGITUDE');
$latitude = $this->post('LATITUDE');
$drcode = $this->post('DRCODE');
$createdon = date('Y-m-d H:i:s');
$insert_array = array('EMPLOYEE_ID' => $employee_id, 'DOCTOR_NAME' => $doctorname, 'DRMOBILE' => $mobilenumber, 'SPECIALITY' => $speciality, 'LONGITUDE' => $longitude, 'LATITUDE' => $latitude, 'CREATEDON' => $createdon);
$users_data = $this->Rest_user_model->doctorregistration($insert_array);
$message = ['status' => 1, // 'result' => $users_data,
'message' => 'Doctor Registered Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
Model
public function doctorregistration($data) {
if (!empty($data)) {
$this->db->insert('DOCTORDETAILS', $data);
return $this->db->insert_id();
}
return 0;
}
Code Generation
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=mysql_query($sql1);
if (!$sql1) { // add this check.
die('Invalid query: ' . mysql_error());
}
$output_array2=array();
while($row=mysql_fetch_assoc($query))
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
Try this - replace this code below with your Code Generation code.
$sql1="SELECT DRCODE FROM DOCTORDETAILS ORDER BY DRCODEDESC LIMIT 1";
$query=$this->db->query($sql1);
if (!$sql1) { // add this check.
die('Invalid query');
}
$output_array2=array();
foreach($query->result_array() as $row)
{
$ids=$row['DRCODE'];
}
// echo $ids;
if($ids){
$su=1;
$num =$num = 'DR' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);;
$unique=$num;
}else{
$unique='DR000001';
}
You should make a different column fr drcode, leave it blank.
Now make a trigger on insert, it should be run after insert.
I am assuming DOCTORDETAILS as table name and drcode as column name
DELIMITER $$
CREATE TRIGGER trigger_after_insert
AFTER INSERT ON `DOCTORDETAILS` FOR EACH ROW
begin
UPDATE `DOCTORDETAILS` set drcode=CONCAT('DR',new.id);
END$$
DELIMITER ;
The trigger create a new string with your new auto generated id
Trigger in MySQL:
TechonTheNet
MySQL Trigger on after insert

Speeding up a very slow PHP script generating a large JSON array

I currently have a web-app running on AppEngine that uses PHP to initially generate a giant JSON array, which Javascript then uses to populate elements of my web-app.
The following code works perfectly and does everything I want, however takes about 10 seconds to execute. Might not sound like a lot, but it certainly feels out of place. I'm wondering what I should be doing differently to speed up the creation of the initial array.
I've so far thought about attacking this a few ways;
I could load less data initially, reducing load times as there is
literally less to load. This would effect the general performance
though, as right now once the data is loaded, each "section" is
instant to be populated and super fast.
I could cache some data using App Engine's
built in Memcache. This is a neat idea however the data generated
changes often. Often enough that a cache just wont do it.
Use Web
Sockets instead. I want to eventually do this, and it's on the to-do
list, however this would mean rewriting a lot of code, so I'm not too
fond of this right now.
I'm sure there are some "bad practise" bits and pieces within my code as well, feel free to point them out and scold me for it... Here's the same code below as a Gist if you prefer it that way.
<?php
use google\appengine\api\cloud_storage\CloudStorageTools;
# ===================================== #
# ==== Generate App Settings Array ==== #
# ===================================== #
//Existing Class (not shown) already generated $app for us...
$app_settings_array = array('app_version' => $app->app_version, 'app_server' => $_SERVER['SERVER_SOFTWARE'], 'app_id' => $app->app_id, 'app_name' => $app->app_name, 'app_logo_dark' => $app->app_logo_dark, 'app_logo_light' => $app->app_logo_light, 'app_motd' => $app->app_motd, 'app_domain' => $app->app_domain);
# ===================================== #
# ==== Generate User Details Array ==== #
# ===================================== #
$currentuser = $_SESSION['user_id']; //Get current user id from session
$user_info = $db->prepare("SELECT * FROM hr_personal WHERE employee_id = :user_id LIMIT 1");
$user_info->bindParam(':user_id', $currentuser);
$user_info->execute();
$user = $user_info->fetch(PDO::FETCH_OBJ);
$email_hash = hash_hmac('sha256', $user->employee_id, '_redactedkey');
$log_info = $db->prepare("SELECT log_time FROM app_log WHERE log_user = :user_id ORDER BY log_time ASC LIMIT 1"); //Get
$log_info->bindParam(':user_id', $currentuser);
$log_info->execute();
$first_seen = $log_info->fetch(PDO::FETCH_OBJ);
$user_details_array = array('id' => $user->employee_id, 'id_hash' => $email_hash, 'first_seen' => $first_seen->log_time, 'title' => $user->employee_title, 'name' => $user->employee_knownas, 'avatar' => $user->employee_avatar, 'mobile' => $user->employee_mobile, 'email' => $user->employee_email);
# ============================= #
# ==== Generate Chat Array ==== #
# ============================= #
$currentuser = $_SESSION['user_id'];
$currentapp = $app->app_id;
$chat_array = array();
foreach (range('A', 'Z') as $char) {
$individuals = array();
$countrow = $db->prepare("SELECT * FROM hr_personal where employee_knownas LIKE '$char%' AND employee_id IN (SELECT notification_submitter FROM notification_sent WHERE notification_id IN (SELECT notification_id FROM notification_wait WHERE user_id = '$currentuser' AND method = 'online' ORDER BY notification_id DESC))");
$countrow->execute();
if ($countrow->rowCount() > 0) {
$mesage_query = "SELECT * FROM hr_personal where employee_knownas LIKE '$char%' AND employee_id IN (SELECT notification_submitter FROM notification_sent WHERE notification_id IN (SELECT notification_id FROM notification_wait WHERE user_id = '$currentuser' AND method = 'online' ORDER BY notification_id DESC))";
$message_query_run = $db->query($mesage_query);
while($row = $message_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['employee_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['employee_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = preg_replace("/^http:/i", "https:", $image_url);
} else {
$image_url = "";
}
$whileUser = $row['employee_id'];
$message_chain = array();
$chain_query = "SELECT * FROM notification_wait WHERE method = 'online' AND user_id = '$currentuser' AND notification_id IN (SELECT notification_id FROM notification_sent WHERE notification_submitter = '$whileUser')";
$chain_query_run = $db->query($chain_query);
while($chainRow = $chain_query_run->fetch(PDO::FETCH_ASSOC)) {
array_push($message_chain, array('id' => $chainRow['notification_id'], 'reply_id' => $chainRow['reply_id'], 'content' => $chainRow['message'], 'time' => $chainRow['time'], 'state' => $chainRow['state']));
}
array_push($individuals, array('id' => $row['employee_id'], 'group' => $char, 'name' => $row['employee_knownas'], 'avatar' => $image_url, 'message_chain' => $message_chain));
}
array_push($chat_array, array('group' => $char, 'data' => $individuals));
}
}
# ========================================== #
# ==== Generate Admin Groups (if admin) ==== #
# ========================================== #
$admin_array = array();
if($auth->checkPage('admin', $_SESSION['user_id']) == false){ //Existing CheckPage class returns true if user is allowed on page
array_push($admin_array, array('access' => 'denied'));
} else {
//Generate All Clients
$client_array = array();
$client_query = "SELECT * FROM clients WHERE client_app = '$currentapp'";
$client_query_run = $db->query($client_query);
while($row = $client_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['client_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['client_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = '<span class="thumbnail-wrapper d48 circular inline m-t-5">
<img id="dynamicavy" src="'.preg_replace("/^http:/i", "https:", $image_url).'" width="48" height="48">
</span>';
} else {
$image_url = "";
}
$short_desc = strlen($row['client_desc']) > 30 ? substr($row['client_desc'],0,30)."..." : $row['client_desc'];
$desc = '<span class="expandable" full-length="'.$row['client_desc'].'">'.$short_desc.'</span>';
$actions = '<button class="btn btn-xs btn-primary">Edit Details</button>';
array_push($client_array, array($row['client_id'], $image_url, "<b>".ucwords($row['client_name'])."</b>", $row['client_dob'], $row['client_phone'], $row['client_address'], $desc, $actions));
}
//Generate All Departments
$department_array = array();
$department_query = "SELECT * FROM departments WHERE dep_app = '$currentapp'";
$department_query_run = $db->query($department_query);
while($row = $department_query_run->fetch(PDO::FETCH_ASSOC)) {
if(!empty($row['dep_avatar'])){
$options = ['size' => 200, 'crop' => true];
$image_file = "gs://rouic-cdn/internal/".$row['dep_avatar'];
$image_url = CloudStorageTools::getImageServingUrl($image_file, $options);
$image_url = '<span class="thumbnail-wrapper d48 circular inline m-t-5">
<img id="dynamicavy" src="'.preg_replace("/^http:/i", "https:", $image_url).'" width="48" height="48">
</span>';
} else {
$image_url = "";
}
$short_desc = strlen($row['dep_description']) > 30 ? substr($row['dep_description'],0,30)."..." : $row['dep_description'];
$desc = '<span class="expandable" full-length="'.$row['dep_description'].'">'.$short_desc.'</span>';
$actions = '<button class="btn btn-xs btn-primary">Edit Details</button>';
array_push($department_array, array($row['dep_id'], $image_url, "<b>".ucwords($row['dep_name'])."</b>", $desc, $actions));
}
array_push($admin_array, array('access' => 'granted', 'allDepartments' => $department_array, 'allClients' => $client_array));
}
... About 4 More sections redacted ...
# ===================== #
# ==== Final Array ==== #
# ===================== #
$init_array_compare = array('chat' => $chat_array, 'admin' => $admin_array, 'app_details' => $app_settings_array, 'user_details' => $user_details_array, 'user_permissions' => $user_permissions_array);
$hash = md5(json_encode($init_array_compare)); //I'm basically creating a hash of the results here so I can see if anything has changed if generated again
$init_array = array('hash' => $hash, 'chat' => $chat_array, 'admin' => $admin_array, 'app_details' => $app_settings_array, 'user_details' => $user_details_array, 'user_permissions' => $user_permissions_array);
echo json_encode($init_array);
MonkeyZeus was completely correct, it turned out to be CloudStorageTools::getImageServingUrl() causing the hanging. After writing a script to cache the URL's it generated the script now runs in under a second.

Simple PHP Cache - Can store data in array but how to retrieve items from that array cache?

I've been able to use the store function of this caching class but I am unable to retrieve a certain item out of the stored array.
$c->setCache("$appid")
->store("$appid", array(
'name' => "$gname",
'price' => "$price",
'logo' => "$glogo",
'link' => "$glink"
)
);
$gcache = $c->retrieve("$appid");
$cprice = $gcache->price; //not sure how to retrieve the price value only
https://github.com/cosenary/Simple-PHP-Cache
Here is the full code where I cannot seem to get the price from the stored array:
<?php
require_once 'cache.class.php';
// Setup 'default' Cache
$c = new Cache();
$glist = "http://steamcommunity.com/id/aksn1p3r/games?tab=all&xml=1";
$gxml = simplexml_load_file($glist);
$tprice = 0;
$i = 0; //just used to exit loop after 2 executions
foreach($gxml->games->game as $game) {
if($i >= 2) {
break;
}
$appid = $game->appID;
$glink = $game->storeLink;
$gname = $game->name;
$glogo = $game->logo;
$gjson = 'http://store.steampowered.com/api/appdetails/?appids=' . $appid;
$fgc = file_get_contents($gjson);
$jd = json_decode($fgc, true);
$gdata = $jd[intval($appid)]['data']; //$appid needs to be integer here, not string
$gdesc = $gdata['about_the_game'];
$gprice = $gdata['price_overview']['final'];
$price = number_format($gprice / 100, 2);
$c->setCache("$appid")
->store("$appid", array(
'name' => "$gname",
'price' => "$price",
'logo' => "$glogo",
'link' => "$glink"
)
);
// this part is where I dont understand how to get the price I stored.
$cprice = $c->retrieve["$appid"]['price'];
$tprice += $cprice;
$i++;
}
echo 'Total games: ' .$i. ' <br>';
echo 'Total Price: ' .$tprice;
?>
You are storing array expecting to get object
Replace
$gcache->price;
with
$gcache['price'];

Displaying array content from function?

Can anyone tell me how to display the value of next from the code below?
In my user.php file i have next content:
class User {
protected $userID;
protected $useremail;
protected $userPassword;
public function __construct() {
$this->userID = preg_replace('#[^0-9]#i', '',
$_SESSION['user_id']);
$this->useremail = preg_replace('#[^A-Za-z0-9#_.-]#i', '',
$_SESSION['user']);
$this->userPassword = preg_replace('#[^A-Za-z0-9]#i', '',
$_SESSION['user_password']);
}
public function UserInfoQuery() {
$sql = "SELECT * FROM users WHERE id =
'$this->userID' AND email = '$this->useremail' AND
password = '$this->userPassword' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
$userMatch = mysql_numrows($res);
if ($userMatch == 1) {
while($row = mysql_fetch_array($res)) {
$userData = array(
$userFirstname = $row['firstName'],
$userLastname = $row['lastName'],
$userBirthdate = $row['birthDate'],
$userSex = $row['sex'],
$userEmail = $row['email'],
$userCountry = $row['country'],
$userRegion = $row['region']);
}
}
return $userData;
}
}
In my index php file when I try:
$User = new User();
print_r($User->UserInfoQuery());
I have next results:
Array ( [0] => firstname [1] =>
lastname [2] =>
1990-11-23 [3] =>
male [4] =>
mail [5] =>
Srbija [6] => town )
How I can echo just the first and last names?
This:
array($userFirstname = $row['firstName'])
assigns the value of $row['firstName'] to the variable $userFirstname, then puts the result of the assignment (the value of $row['firstName']) into an array. It's the same as writing:
$userFirstname = $row['firstName'];
array($row['firstName']);
To declare an array with the key userFirstname, you need to write:
array('userFirstname' => $row['firstName'])
From here, you have a normal array you can access:
$userinfo = $User->UserInfoQuery();
echo $userinfo['userFirstname'];
This does seem somewhat clunky though, and honestly, you're not using objects very well here. You should save the data queried from the database into properties of the object, then use getters to access those properties one by one or all together. How to design a proper object is a little beyond the scope/point of this answer though.
You should have your array the following way:
$userData = array(
'Firstname' = $row['firstName'],
'lastname = $row['lastName'],
'birthdate = $row['birthDate'],
'sex = $row['sex'],
'email = $row['email'],
'country = $row['country'],
'region = $row['region']
);
}

Categories