How to send rows using json_encode method in php? - javascript

I have number of rows in investment table. I need to retrieve all of them and send them back using json_encode.
Here is my code
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
while($x1 = mysql_fetch_array($result))
{ $detail = $x1['detail'];
$sector = $x1['sector'];
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
In javascript I wrote following script:
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('display_acc.php',{id:value},function(data)
{
data = JSON.parse(data);
$( '#a' ).html(data.a);
$( '#b' ).html(data.b);
});
});
Here my problem is that it returns only data of last rows. I want to receive data of all rows.
I have to display id a and b here
I use table to display it.
Thank in advance

This should do the trick:
--EDIT after OP explanation--
PHP
$project_code = (int)$_GET['id']; //better put (int) before to avoid SQL Injection
$sql = "select detail, sector from investment where project_code = '$project_code'"; //better to maintain if you set only the fields you will use
$result = mysql_query($sql);
$return = array('detail'=> array(), 'sector' => array()); //here you can put empty return array or set detail and sector key. Your choice will have impact in your front-end
$return['my_extra_var' ] = $my_extra_var;
$i = 0;
while($x1 = mysql_fetch_array($result))
{
$return['table'][$i]['detail'] = $x1['detail'];
$return['table'][$i]['sector'] = $x1['sector'];
$i++;
}
echo json_encode($return);
Javascript
... your ajax request ...
data = JSON.parse(data);
var tableData = data.table;
$.each(tableData, function(index, value) {
$('#tableData').append('<tr><td>'+value.detail+'</td><td>'+value.sector+'</td></tr>'); //append row to tbody
});
HTML
<table>
<thead>
<th>Details</th>
<th>Sector of Investment</th>
</thead>
<tbody id="tableData">
</tbody>
</table>

You need arrays in your loop
$project_code = $_GET['id'];
$sql = "select * from investment where project_code = '$project_code'";
$result = mysql_query($sql);
$cnt=0;
while($x1 = mysql_fetch_array($result))
{ $detail[$cnt] = $x1['detail'];
$sector[$cnt] = $x1['sector'];
$cnt++;
}
echo json_encode(array(
'a' => $detail,
'b' => $sector
));
and in javascript loop over the result

It looks like you are not accumulating the two elements. Try something like this:
array_push(your_array_name, $detail, $sector);
Then encode your array when all done.

Related

Trying to transfer mysql database data to javascript array

I have tried few things bet they don't seem to work, my code works fine if I populate the array myself without database therefore the problem is with retrieving data from database.
var countries = <?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
while($products = mysqli_fetch_array($result, MYSQLI_NUM)){
echo json_encode($products);
//OR
//$products = mysqli_fetch_all($result, MYSQLI_NUM);
//echo json_encode($products);
}
?>;
This is the code I have tried but it is not working
I am sending countries to a function
autocomplete(document.getElementById("myInput"), countries);
In this function I am parsing through the array in such a way
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
/*here arr is the array 'countries' send to the function autocomplete*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {//code snippet
}}
You are echoing a JSON string at each iteration of the while() loop. So, it will writes a non-valid JSON string. You could create an array, populate it, and finally, write it as JSON:
<?php
require('connection.php');
$query = 'SELECT product_name FROM products';
$result = mysqli_query($conn, $query);
$products = []; // new array
while($product = mysqli_fetch_array($result, MYSQLI_NUM)) {
$products[] = $product ; // push into array
}
// finally, write JSON:
?>
var countries = <?php echo json_encode($products) ?>;

How to take individual values from MYSQL and save it to a JavaScript variable?

I want to select the last row of my table, and save all the values to separate JavaScript variables. I used the query in PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
to select the last row of the table. I don't know how to proceed.
PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
echo json_encode($row);
}
jQuery:
// sample variables
var username = "";
var password = "";
var phpUrl = 'http://sampleurl.com/mypage.php';
$.getJSON(phpUrl, function (result) {
$.each(result, function (data) {
// if data sent back is eg data:[{username:'sample', password:'sample'}]
// then you fetch and save as
username = data.username;
password = data.password;
});
});
cookies way is definitely the way to go. If you are doing all of this on one page and just need a quick fix you could do
<?php
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
$json_string = json_encode($row);
}
?>
<script> var sql_row = <?php echo $json_string; ?>; </script>
This is the lazy way and will get messy quickly, but it could be useful for understanding how PHP and JS work together

PHP JSON into javascript variable

befora I ask this i tried every solution on google and here on stackoverflow.
So in my js file I have this
var locations = [
['Name','Country','City','lat','lng'],
['Name','Country','City','lat','lng'],
];
When i wrote this in file manually my mapp shown locations but I need to generate content of locations variable from mysql in php, is there something that I missing.I tried with ajax,console.log...etc
My PHP file
$result = mysqli_query($link, "SELECT hospital_name,country,city,lat,lng FROM hospitals");
$to_encode = array();
while($row = mysqli_fetch_row($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
I tried this but no success
$.getJSON( "process.php", function( json ) {
var locations = json;
});
I just switched your mysqli_fetch_row to mysqli_fetch_array
$result = mysqli_query($link, "SELECT hospital_name,country,city,lat,lng FROM hospitals");
$to_encode = array();
while($row = mysqli_fetch_array($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);

cant fillter characters in jcombo

Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.

json_encode a MySQL table and urldecode Each Row

Here's what I got. I have a MySQL table, in this case 'businesses' which has a many rows of urlencode() data. I am trying to use a php script (getTable.php) to grab the table urldecode() each row and then use a json_encode to send the data as an array back to javascript. Here's what i have so far.
$table = $_GET['table'];
$query = "SELECT * FROM $table";
$jsonOut = array();
while($result = mysql_fetch_array(mysql_query($query)))
{
foreach($result as &$value)
{
$value = urldecode($value);
}
$jsonOut[] = $result;
}
echo (json_encode($jsonOut));
Obviously, I'm doing something wrong because I'm causing an infinite loop and nothing ends up working. Any help wold be greatly appreciated.
Try this code:
$table = $_GET['table'];
$query = "SELECT * FROM $table";
$jsonOut = array();
$result = mysql_query($query);
while($result = mysql_fetch_array($result))
{
$jsonOut[] = $result;
}
echo (json_encode($jsonOut));
In fact the query has to be executed only once, not once for each iteration of the while loop, or else you'll end up with an infinite loop!
Also, as a side note, you should avoid using mysql_* functions as they're now deprecated, try to switch to PDO if you can.
EDIT:
If you need to urldecode each row, replace
$jsonOut[] = $result;
with
$jsonOut[] = array_map('urldecode', $result);
inside the while loop.
This is the infinite loop you're talking about
while($result = mysql_fetch_array(mysql_query($query)))
Try
$recordset=mysql_query($query);
while($result = mysql_fetch_array($recordset)){
}
Note: MySQL API is long deprecated, better move away from it before you are forced to
You should do like this:
$query = mysql_query($query);
while($result = mysql_fetch_array($query)) {
You could retrieve and decode your parameters with the following code. (Based on #Matteo Tassinari answer)
$table = $_GET['table'];
//This could be a SQL injection
$query = "SELECT * FROM " . mysql_real_escape_string($table);
$jsonOut = array();
$result = mysql_query($query);
while($result = mysql_fetch_array($result))
{
$newArray = array();
foreach ($result as $k => $v) {
$newArray[$k] = urldecode($v);
}
$jsonOut[] = $newArray;
}
echo (json_encode($jsonOut));

Categories