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>
Related
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 working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);
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);
I want to encode an array in php as JSON. How do I make a proper JSON array?
i want to pass two variables.
$var = 33;
$last = 44;
and db results:
foreach($query->result() as $r)
{
$data[]= $r; //popunjava niz rezultatima
}
i am trying to make JSON like this:
$data='';
$data[] =$last;
$data[] =$pn;
foreach($query->result() as $r)
{
$data[]= $r; //popunjava niz rezultatima
}
echo json_encode($data); // json enkoduje niz i pomocu echo prosledjuje do ajaxa
Use array_push to append rows onto the array.
$data = array();
foreach($query->result() as $r)
{
array_push($data, $r);
}
echo json_encode($data);
You should set a key in the array for the variables that you add.
$data= array();
$data['last'] = $last;
$data['pn'] = $pn;
foreach($query->result() as $r)
{
$data['results'][] = $r;
}
echo json_encode($data);
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.