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);
Related
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.
Let say,
My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.
How can I store in Javascript after I converted them into json by
<?php
$sql = "SELECT public_holiday.holiday_date
FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
$json_array = json_encode($result_array);
echo $json_array;
?>
?
I have tried to store them into a javascript date array like
var holidays = [<?php //sample array for example
$loop_one = true;
foreach ($result_array as $date)
{
if ($loop_one)
{
echo "'new Date(\'$date\')'";
$loop_one=false;
}
else
{
echo ", 'new Date(\'$date\')'";
}
}
?>];
but all of these are invalid.
I need your help, much appreciated.
To get a javaScript date object array you need to change your script code only no need to change the PHP code.
You can use JSON.parse and forEach loop.
Try like this
<script>
var holidays = '<?php echo $json_array;?>';
holidays=JSON.parse(holidays);
var holidayArray=[];
holidays.forEach(function (key) {
holidayArray.push(new Date(key));
});
console.log(holidays);
console.log(holidayArray);
</script>
It will produce an out put as
I thing it will help you.
So in your sample, the $result_array variable will be a PHP array like:
$result_array = ['2017-06-25', '2017-06-26', '2017-06-27'];
You do not really need to convert this to JSON before passing it to your Javascript. Instead, you could print those string values directly into your Javascript to instantiate the date object, i.e.
<?php
$sql = "SELECT holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['holiday_date']; # Return the actual date value and not an array
}
?>
Javascript Part:
var holidays = [<?php
$firstLoop = true;
foreach ($result_array as $date_result) {
# Here you could format your $date_result variable as a specific datetime format if needed to make it compatible with Javascripts Date class.
if ($firstLoop) {
$firstLoop = false;
echo "new Date('$date_result')";
} else {
echo ", new Date('$date_result')";
}
}
?>];
In this example, I'm constructing a javascript array of new Date($phpDateTime) objects.
Your while loop should be like this and push the date into new array
<?php
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
//$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];
?>
Javascript example
<script>
var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
Update 1: Finally your code should be like this
<?php
$sql = "SELECT public_holiday.holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
?>
<script>
var holidays = [<?php
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
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 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> */
}
);