Can someone please tell me what I'm doing wrong here? I have an ajax function which runs every few seconds and it basically checks 2 database tables and if they do not match then update one of the database tables to match the other database table, but for some reason it doesn't update the database table. How do I edit the function so I can achieve this?
Here are the functions inolved:
function tb_update_old_followers($user_id) {
$followers = tb_get_follower_count($user_id);
$old_followers = tb_get_old_follower_count($user_id);
$response['new_new_followers'] = $followers;
$response['old_new_followers'] = $old_followers;
$response = json_encode( $response );
echo $response;
update_user_meta( $user_id, '_tb_old_followed_by_count', $followers + 1);
die();
}
add_action('wp_ajax_tb_update_old_followers' , 'tb_update_old_followers');
function tb_get_follower_count( $user_id = null ) {
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
$followed_count = get_user_meta( $user_id, '_tb_followed_by_count', true );
$count = 0;
if ( $followed_count ) {
$count = $followed_count;
}
return (int) apply_filters( 'tb_get_follower_count', $count, $user_id );
}
function tb_get_old_follower_count( $user_id = null ) {
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
$old_followed_count = get_user_meta( $user_id, '_tb_old_followed_by_count', true );
$old_count = 0;
if ( $old_followed_count ) {
$old_count = $old_followed_count;
}
return (int) apply_filters( 'tb_get_old_follower_count', $old_count, $user_id );
}
Any help would be greatly appreciated!
The reason is simple. You haven't defined user_id inside tb_update_old_followers() function. Just do it and it would work.
function tb_update_old_followers() {
$user_id=get_current_user_id();
$followers = tb_get_follower_count($user_id);
$old_followers = tb_get_old_follower_count($user_id);
$response['new_new_followers'] = $followers;
$response['old_new_followers'] = $old_followers;
$response = json_encode( $response );
echo $response;
update_user_meta( $user_id, '_tb_old_followed_by_count', $followers + 1);
die();
}
Related
I have tried this code but receiving error.
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data = [];
foreach($row as $key) {
$data[] = [
'first_name' => $key['first_name'],
'last_name' => $key['last_name']
];
}
echo json_encode($data);
How can I json encode specific keys using php ?
I have solved..
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name']
);
echo json_encode($data);
This code is working very well..
I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>
How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
When I pass data into my file upload controller, it is giving an error of undefined offset: 1.
function TestFileUpload() {
$i=0;
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
$count = count($_FILES[$i]['name']). ' ';
while ($i <= 4 )
{
echo $count;
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
echo $_FILES[$i]['name'].' '.$_FILES[$i]['type'].' '.$_FILES[$i]['size'] ;
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else{
$data = array('upload_data' => $this->upload->data());
$this->new_development_model->insertonAttachments($data['upload_data']);
$i++;
}
}
}
}
It's probably related cause you need to check in your loop if $_FILES[$i] is defined.
You do this but only one time, when $i = 0.
I even think that if you check in the loop, you wont need to do
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else { /*...*/ }
before the loop
I'm trying to create a gameserver query for my website, and I want it to load the content, save it, and echo it later. However, it doesn't seem to be echoing. It selects the element by ID and is supposed to echo the content of the VAR.
Here's my HTML code:
<center><div id="cstrike-map"><i class="fa fa-refresh fa-spin"></i> <b>Please wait ...</b><br /></div>
JavaScript:
<script type="text/javascript">
var map = "";
var hostname = "";
var game = "";
var players = "";
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
map = ( data.map );
hostname = ( data.hostname );
game = ( data.game );
players = ( data.players );
}, "json");
function echoMap(){
document.getElementByID("cstrike-map");
document.write("<h5>Map: " + map + "</h5>");
}
</script>
PHP files:
query.php
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut = explode(":", $ip);
$HL2_address = $cut[0];
$HL2_port = $cut[1];
$HL2_command = "\377\377\377\377TSource Engine Query\0";
$HL2_socket = fsockopen("udp://".$HL2_address, $HL2_port, $errno, $errstr,3);
fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket,4);
$CheckStatus = socket_get_status($HL2_socket);
if($CheckStatus["unread_bytes"] == 0)
{
return 0;
}
$do = 1;
while($do)
{
$str = fread($HL2_socket,1);
$HL2_stats.= $str;
$status = socket_get_status($HL2_socket);
if($status["unread_bytes"] == 0)
{
$do = 0;
}
}
fclose($HL2_socket);
$x = 0;
while ($x <= strlen($HL2_stats))
{
$x++;
$result.= substr($HL2_stats, $x, 1);
}
$result = urlencode($result); // the output
return $result;
}
/* FORMAT SOURCE ENGINE QUERY (assumes the query's results were urlencode()'ed!) */
function format_source_query($string)
{
$string = str_replace('%07','',$string);
$string = str_replace("%00","|||",$string);
$sinfo = urldecode($string);
$sinfo = explode('|||',$sinfo);
$info['hostname'] = $sinfo[0];
$info['map'] = $sinfo[1];
$info['game'] = $sinfo[2];
if ($info['game'] == 'garrysmod') { $info['game'] = "Garry's Mod"; }
elseif ($info['game'] == 'cstrike') { $info['game'] = "Counter-Strike: Source"; }
elseif ($info['game'] == 'dod') { $info['game'] = "Day of Defeat: Source"; }
elseif ($info['game'] == 'tf') { $info['game'] = "Team Fortress 2"; }
$info['gamemode'] = $sinfo[3];
return $info;
}
cstrike.php
include('query.php');
$ip = 'play1.darkvoidsclan.com:27015';
$query = source_query($ip); // $ip MUST contain IP:PORT
$q = format_source_query($query);
$host = "<h5>Hostname: ".$q['hostname']."</h5>";
$map = "<h5>Map: ".$q['map']."</h5>";
$game = "<h5>Game: ".$q['game']."</h5>";
$players = "Unknown";
$stats = json_encode(array(
"map" => $map,
"game" => $game,
"hostname" => $host,
"players" => $players
));
You need to display the response in the $.post callback:
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
$("#map").html(data.map);
$("#hostname").html(data.hostname);
$("#game").html(data.game);
$("#players").html(data.players);
}, "json");
You haven't shown your HTML, so I'm just making up IDs for the places where you want each of these things to show.
There are some things that I can't understand from your code, and echoMap() is a bit messed up... but assuming that your php is ok it seems you are not calling the echomap function when the post request is completed.
Add echoMap() right after players = ( data.players );
If the div id you want to modify is 'cstrike-map' you could use jQuery:
Change the JS echoMap to this
function echoMap(){
$("#cstrike-map").html("<h5>Map: " + map + "</h5>");
}
So what I did was I had to echo the content that I needed into the PHP file, then grab the HTML content and use it.
That seemed to be the most powerful and easiest way to do what I wanted to do in the OP.
<script type="text/javascript">
$(document).ready(function(){
$.post("stats/query.cstrike.php", {},
function (data) {
$('#serverstats-wrapper-cstrike').html (data);
$('#serverstats-loading-cstrike').hide();
$('#serverstats-wrapper-cstrike').show ("slow");
});
});
</script>
PHP
<?php
include 'query.php';
$query = new query;
$address = "play1.darkvoidsclan.com";
$port = 27015;
if(fsockopen($address, $port, $num, $error, 5)) {
$server = $query->query_source($address . ":" . $port);
echo '<strong><h4 style="color:green">Server is online.</h4></strong>';
if ($server['vac'] = 1){
$server['vac'] = '<img src="../../images/famfamfam/icons/tick.png">';
} else {
$server['vac'] = '<img src="../../images/famfamfam/icons/cross.png">';
}
echo '<b>Map: </b>'.$server['map'].'<br />';
echo '<b>Players: </b>'.$server['players'].'/'.$server['playersmax'].' with '.$server['bots'].' bot(s)<br />';
echo '<b>VAC Secure: </b> '.$server['vac'].'<br />';
echo '<br />';
} else {
echo '<strong><h4 style="color:red">Server is offline.</h4></strong>';
die();
}
?>