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.
Related
This is my code:
if (preg_match('/^\/start (.*)/', $text, $match) or preg_match('/^\/get_(.*)/', $text, $match)) {
$id = $match[1];
if (isJoin($from_id)) {
$fileData = mysqli_query($db, "SELECT * FROM `file` WHERE `id` = '{$id}'");
$file = mysqli_fetch_assoc($fileData);
if (mysqli_num_rows($fileData)) {
if ($file['password']) {
sendMessage($from_id, "please send pass :", "markdown", $btn_back, $message_id);
mysqli_query($db, "UPDATE `user` SET `step` = 'password', `getFile` = '$id' WHERE `from_id` = '$from_id'");
} else {
$downloads = number_format($file['downloads']);
$downloads++;
$caption = urldecode($file['caption']);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id'],
'caption' => "š„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id2'],
'caption' => "š„ count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
mysqli_query($db, "UPDATE `file` SET `downloads` = `downloads`+1 WHERE `id` = '$id'");
mysqli_query($db, "UPDATE `user` SET `step` = 'none', `downloads` = `downloads`+1 WHERE `from_id` = '$from_id'");
}
} else sendMessage($from_id, "hi welcome to bot", 'markdown', $btn_home, $message_id);
} else {
joinSend($from_id);
mysqli_query($db, "UPDATE `user` SET `getFile` = '$id' WHERE `from_id` = '$from_id'");
}
}
so what i want to do is repeat this code like 24 times but each time the number at the end of file_id changes like file_id1, file_id2, file_id3, ..., file_id24.
and the values for file_id1, ... and others are stored on my SQL database.
Now if you see there is two codes repeating and the only change is the number at the end of file_id so i want to make it 24 codes but instead of just repeating it I want to do it with one code.
and another thing I said 1 to 24 can i also do something so it reads the last number from a database value to like loop from 1 to x and x is the number i entered in database.
sorry i'm new to programming.
All you need to do is wrap that code in a for loop that increments 1..N. Then in the body of the loop, append / interpolate the loop increment variable where you need it.
for ($i = 1; $i <= 24; $i++) {
// ...
("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file["file_id$i"],
'caption' => "š„ Count : <code>{$downloads}</code>\n{$caption}\nš” Thanks",
'parse_mode' => "html",
]);
}
I'm using following package : 'osiset/Basic-Shopify-API' and need bulk update products by location.
It's only possible with GraphQL. This function should work :
inventoryBulkAdjustQuantityAtLocation Shopify documentation
$shop = 'example.myshopify.com';
$token = 'shppa_admin_api_token';
/ Create options for the API
$options = new Options();
$options->setVersion('2020-04');
// Create the client and session
$api = new BasicShopifyAPI($options);
$api->setSession(new Session($shop, $token));
$products[0]['inventoryItemId'] = '33125243617303';
$products[0]['availableDelta'] = 2000;
$result = $api->graph(
'mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: InventoryAdjustItemInput!,$locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $InventoryAdjustItemInput, locationId: $locationId) {userErrors {field message } inventoryLevels { id }}}',
['inventoryItemAdjustments' =>
$products
],
);
But I don't understand how to use it. Could anyone help me ?
Now it works. It's a challenge to understand GraphQL queries if you never used them before.
Here are some more information :
https://www.shopify.com/partners/blog/multi-location_and_graphql
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments1['locationId'] = $locationId;
$inventoryItemAdjustments1['inventoryItemAdjustments']['inventoryItemId'] = 'gid://shopify/InventoryItem/1';
$inventoryItemAdjustments1['inventoryItemAdjustments']['availableDelta'] = 500;
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$inventoryItemAdjustments1
);
Not so good examples (hardcoded values, aliases - not real life examples) ... graphql variables should be used and they should match mutation requirements ('root' parameters), in this case locationId and inventoryItemAdjustments (array of objects).
You can test this mutation in graphiql/playground using 'query variables' defined like this:
{
locationId: "gid://shopify/Location/1",
inventoryItemAdjustments: [
{
'inventoryItemId': 'gid://shopify/InventoryItem/1',
'availableDelta': 500
},
{
'inventoryItemId': 'gid://shopify/InventoryItem/2',
'availableDelta': 100
}
]
}
... so using php (associative arrays are encoded to json as objects - explicitely declared for readability) it should look more like this:
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments = [];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/1',
'availableDelta'] => 500;
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/2',
'availableDelta'] => 100;
];
$variables = (object)[
'locationId' => $locationId;
'inventoryItemAdjustments' => $inventoryItemAdjustments
];
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$variables
);
I would like to show another library that uses this and expand on the last example.
I am using a slightly different library for graphql:
https://github.com/Shopify/shopify-php-api/
Updating the inventory like it was posted here shows a [statusCode:GuzzleHttp\Psr7\Response:private] => 200
So it seems to work but does not reflect in updated inventory. :(
Checking at /admin/products/inventory?location_id=62241177806&query=F11_27781195
would not show the new inventory.
I am using the inventoryid correctly (not product or variantid).
$inventoryItemAdjustments = array();
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435235534',
'availableDelta' => 500
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435268302',
'availableDelta' => 500
];
$variables = array(
'locationId' => ConfigClass::$locationId,
'inventoryItemAdjustments' => $inventoryItemAdjustments
);
$graphqlquery='mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}';
$response = $client->query(['query' => $graphqlquery, 'variables' => $variables]);
Deleting a product works (and is a good test if the library is initialized well):
$query = <<<QUERY
mutation {
productDelete(input: {id: "gid://shopify/Product/6975310463182"})
{
deletedProductId
}
}
QUERY;
$response = $client->query(["query" => $query]);
print_r($response);
die;
I've taken over managing our site from MIA developers and have spent the day trying to find this answer.
After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).
Here's what I know:
Drupal Version 7.56
PHP 7.0.20
No errors when status report is run
Chron - no errors
Here's what I've done:
added $cookie_domain = '.example.com'; to settings.php
cleared browser cache and cookies
ensured admin has access to everything
cleared site cache
made sure code on page(s) was exactly the same as it was before I did the update
Not sure what to do or where to go from here. Any help is much appreciated.
UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.
Image 1: viewing page as admin
Image 2: viewing page as superadmin
function custom_reports_menu() {
$items['administration/upcoming-classes'] = array(
'title' => 'Upcoming Classes',
'page callback' => 'custom_reports_upcoming_classes_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.upcoming-classes.inc',
'type' => MENU_CALLBACK,
);
$items['administration/class-details'] = array(
'title' => 'Class Details',
'page callback' => 'custom_reports_class_details_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.class-details.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_reports_upcoming_classes_page() {
drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));
global $user;
$uid = $user->uid;
$output = '';
$upcoming_classes = custom_reports_get_upcoming_classes();
$attendee_count = custom_reports_get_attendee_count();
// upcoming classes
$output .= '<h2>Upcoming Classes</h2>';
$output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);
return $output;
}
function custom_reports_permission() {
return array(
'admin wdcc reports' => array(
'title' => t('Admin WDCC Reports'),
'description' => t('Perform administration tasks for WDCC.'),
//'cache' => DRUPAL_NO_CACHE,
),
);
}
function custom_reports_get_upcoming_classes() {
$today = date('Y-m-d');
$x = 0;
$classes = '';
// get classes from new db tables
$today = date('Y-m-d H:i:s');
$result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$nid = $row->nid;
$node = node_load($nid);
$product_id = $nid;
$product_title = $node->title;
$product_type = 'public_class_date';
$product_date = $node->field_date[$node->language][0]['value'];
$product_datestamp = strtotime($product_date);
//$product_datestamp = strtotime($product_date);
// set vars
$classes[$x]['product_id'] = $product_id;
$classes[$x]['product_title'] = $product_title;
$classes[$x]['product_type'] = $product_type;
$classes[$x]['product_date'] = $product_date;
$classes[$x]['product_datestamp'] = $product_datestamp;
$x++;
}
}
return $classes;
}
function custom_reports_get_attendee_count() {
$attendees = array();
$old_attendees = array();
$new_attendees = array();
$result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$item_id = $row->itemID;
$attendee_id = 'B'.$row->attendeeID;
$attendee_name = $row->attendeeName;
$old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;
if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
} else {
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
}
}
}
if (is_array($old_attendees)) {
$connect_class_ids = custom_accounts_connect_class_ids();
foreach ($old_attendees as $old_item_id => $attendee_list) {
if (isset($connect_class_ids[$old_item_id])) {
$product_id = $connect_class_ids[$old_item_id];
foreach ($attendee_list as $attendee_id => $attendee) {
$old_attendee_id = $attendee['old_attendee_id'];
$attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
}
}
}
}
$result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->id;
$product_id = $row->product_id;
$attendees[$product_id][$attendee_id]['total_attendees'] = 1;
}
}
$cancelled_attendees = array();
$result = db_query("SELECT * FROM wdcc_attendees_cancelled");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->attendee_id;
$old_attendee_id = 'B'.$row->old_attendee_id;
if ($attendee_id > 0) {
$cancelled_attendees[] = $attendee_id;
} else {
$cancelled_attendees[] = $old_attendee_id;
}
}
}
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (in_array($attendee_id, $cancelled_attendees)) {
unset($attendees[$product_id][$attendee_id]);
}
}
}
$attendee_count = array();
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (!isset($attendee_count[$product_id])) {
$attendee_count[$product_id] = $attendee['total_attendees'];
} else {
$attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
}
}
}
return $attendee_count;
}
function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {
$output = '';
if (is_array($upcoming_classes)) {
$output .= '<div class="table-responsive table-container">';
$output .= '<table class="table">';
$output .= '<tr><td>Class</td><td>Guests</td><td>Actions</td></tr>';
foreach ($upcoming_classes as $class) {
$nid = $class['product_id'];
$node_url = url('node/'.$nid, array('absolute' => TRUE));
$attendees = 0;
if (isset($attendee_count[$nid])) {
$attendees = $attendee_count[$nid];
}
$output .= '<tr><td>'.$class['product_title'].'<br />'.date('m/d/Y - g:i A', $class['product_datestamp']).'</td><td>'.$attendees.'</td><td>View roster</td></tr>';
}
$output .= '</table>';
$output .= '</div>';
} else {
$output .= '<p>No upcoming classes found.</p>';
}
return $output;
}
Probably would need more info, but it seems like a case of custom or hardcoded permissions.
Here's potential cases to explore:
Assign all the roles to the admin user
Search custom modules for this page URL. See if page is only certain users are allowed to access this page.
If report is Drupal View, find this view and check the permissions section.
In the current menu items you are using access callback attribute in a wrong way. Your menu items do not require to specify access callback. Only access argument is sufficient.
Please add an access argument to which only admin has access.
"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).
Source: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
Replace this below code in settings.php file
PHP variable name:
$cookie_domain = 'example.com'; (line 340)
I was getting this error while login Drupal. After lots of reacher I found that we mistakenly blocked some internal IP of Drupal which is trigger while login the Drupal. So my suggestion is here Your should have to check if you have block any IP at your end (index.php file or anywhere). And You can TRUNCATE the Table session and flood from DB it also help you out.
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.
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']
);
}