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));
Related
I want to build an array in PHP from SQL query and send it back via ajax to my JS file.
$id = clear(filter_input(INPUT_POST, 'id'));
$sql = 'SELECT * FROM `counties` WHERE `id`="'.$id.'"';
$query = mysqli_query($con, $sql);
$array = array();
while($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$name = $result['name'];
$array[] = array('id' => $id, 'name' => $name);
}
echo json_encode($array);
This is my code. In response I have always just one element. There's a lot of more. How could i do that correctly? I was browsing whole Internet and I didn't find anything useful... :(
$id = $_POST['id'];
$query = mysqli_query($con, "SELECT id,name FROM `counties` WHERE `id`='$id'");
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo json_encode($array);
this may simplified code
I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.
EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments
NOTE: I'm using AngularJS to post
This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
EDIT 2: I managed to solve the issue on my own. Here is the solution:
I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
here is php code:
<?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
$ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';
$sql = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_object()) {
$data[] = $row;
}
} else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
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
I am new to PHP and Highchart. Currently, I am trying to:
1. Query my data from MySQL using PHP.
2. To display HighChart :: Javascript, get data from json_encode in PHP.
Problem now, my PHP is 5.1.6 (I have a few applications running since few years back, try not to upgrade the php). I cannot use the json_numeric_check.
Help Needed :
Question 1: is there any alternative way to get the value without json_numeric_check?
Question 2: Is there any package I can add in to php 5.1.6 to use json_numeric_check?
This is the code I want to use ::
print json_encode($result,json_numeric_check);
My Full Code
<?php
header("Content-Type:application/json");
include_once "shift.php";
list($s1,$e1,$shift) = shift_frame();
$servername = 'localhost';
$username = "";
$password = "";
$select = "SELECT EH_CELLNUM, COUNT(EH_SERIALID)";
$table = " FROM T_EEDATA";
$rule1 = " WHERE (EH_END_DT between ".$s1." and ".$e1.") group by EH_CELLNUM";
$conn = mysql_connect($servername,$username,$password) or die("Connection failed: " . mysqli_connect_error());
mysql_select_db("eedata",$conn) or die(mysql_error());
$sql = $select.$table.$rule1;
$query = mysql_query( $sql, $conn );
$category = array();
$category['name'] = 'Cellnum';
$series1 = array();
$series1['name'] = 'SerialID';
while($row = mysql_fetch_array($query)){
$category['data'][] = $row['EH_CELLNUM'];
$series1['data'][] = $row['COUNT(EH_SERIALID)'];
}
////////////code add here???/////////////////////////////
$result = array();
array_push($result,$category);
$result2 = array();
array_push($result,$series1);
print json_encode($result,json_numeric_check);
mysql_close($conn);
?>
you can do someting to $result before json_encode
for example:
$result = array("1", "2", "3", "4");
$result = array_str_to_int($result);
// only for simple array,you can optimize the code
function array_str_to_int($array){
$tmp_arr = array();
foreach( $array as $k => $v ){
$tmp_arr[] = intval($v);
}
return $tmp_arr;
}
In php, i have used an sql query to fetch the data like :-
$sql="Select * from xyz";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
}
Now i want to use all the values attained using $row["id"] in javascipt function and use it in a variable (var j , lets say). How to do this?
Try something like this:
<?php
$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$errorData[]=$row["id"]
}
$errorJson = json_encode($errorsData);
?>
<script>
var errorJson = <?= $errorJson ?> ;
console.log(errorJson);
<script>
Good luck!!
in jquery I would have done like this,
php
$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$arr_json[] = $row['id'];
}
echo json_encode($arr_json);
jquery
$.get(
<THAT CALLED URL>,
function(ret_data){
console.log(ret_data);
/* you can use the ret_data as ret_data.<INDEX> */
}
);