How to json encode Specific Key value using PHP? - javascript

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..

Related

I want to display the following data in table

I want to display the following data in a table.
I have tried fetching data from database but only one column is visible
# AJAX CODE
$.ajax({
url:'process/getState.php',
method:'GET',
success:function(response){
res = JSON.parse(response);
console.log(res);
$.each(res,function(k,v){
var t = $('.template > table > tbody > tr').clone();
t.find('.state').html(v.state);
t.find('.count').html(v.count);
$('#tbody').append(t);
console.log(v);
});
}
})
# PROCESS FILE
<?php
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql);
$state = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($state,$row);
}
die(json_encode($state));
} else {
echo "0 results";
}
$conn->close();
?>
I am only getting the data in the state column but the count column is turning out to be blank
You are seeing one column or row because your $state is not declared properly as an array
Simply edit your process file to look like this:
include('connection.php');
$conn = connection();
$sql = "SELECT * FROM statedistribution";
$result = $conn->query($sql) or die ("Error :".mysql_error());
$state = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$state[] = $row;
}
$output = json_encode($state);
} else $output = "0 results";
$conn->close();
echo $output;

Update User Meta Via Ajax

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();
}

Google Line Chart won't group by month when using data from mysql with php. Only shows all dates

I have the following php and javascript coding to build a Google line chart from mySql data. It works but it gives me every date and I need it to be grouped by month. How do I adjust my code to have "January", "February", "March", etc. on the x-axis?
(Connection is functional)
<?php
....
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: ". mysqli_connect_error());
}
$query = "SELECT SUM(day_hours) AS 'hours',
date FROM monthly_totals WHERE date >='2018-01-01'
GROUP BY date
ORDER BY date";
$sql = mysqli_query($conn, $query);
$results = array('cols' => array(
array('label' => 'Date', 'type' => 'datetime'),
array('label' => 'Total Hours', 'type' => 'number')
),
'rows' => array()
);
while($row = mysqli_fetch_assoc($sql))
{
$dateArr = explode('-', $row['date']);
$year = (int) $dateArr[0];
$month = (int) $dateArr[1] - 1;
$day = (int) $dateArr[2];
$date = "Date($year,$month,$day)";
$results['rows'][] = array('c' => array(
array('v' => $date),
array('v' => $row['hours'])
));
}
$jsonTable = json_encode($results)
?>
Javascript:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable;?>);
var options = {
title:'Hours per Month',
legend:{position:'bottom'},
chartArea:{width:'95%', height:'65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
</script>
I was able to pull the data I needed by updating the SELECT statement and removing date references from the php code:
$query = "SELECT SUM(day_flight_hours) AS 'hours',
MONTHNAME(flight_date) AS 'month' FROM monthly_totals
WHERE flight_date>='2018-01-01' GROUP BY MONTHNAME(flight_date)
ORDER BY flight_date";
$sql = mysqli_query($conn, $query);
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Hours', 'type' => 'number')
);
while($row = mysqli_fetch_assoc($sql)) {
$temp = array();
$temp[] = array('v' => (string) $row['month']);
$temp[] = array('v' => (int) $row['hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table)

JSON array accent display

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;
?>

Having json inside autocomplete

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);
}
?>

Categories