Can't include more than one PHP string in dataset - javascript

I'm trying to create a D3.js chart that requires data from a MySQL database. The chart is made using JavaScript, but I want to replace the values with the database value.
This works if I only try to input one value using PHP, but not if I add any more.
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
]; // This works
The above works, however, this doesn't:
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
]; // Adding another PHP value stops the entire chart from working (it works if I use a non-PHP second value).
I also attempted to just use one single while loop for all data, but that didn't work either.
<?php $connect = mysqli_connect("host", "user", "pass", "db");
$query = "SELECT data1, data2 FROM database WHERE x = y;
$result = mysqli_query($connect, $query); ?>
I know for sure that the data isn't the issue. I've tried the same thing on Google Charts and it worked without issue.

#create an array for the objects
$datasets=array();
#very unclear if your code fetches one or more rows,
#it seems one row with dataX fields
$row = mysqli_fetch_array($result);
#So we go over it
foreach($row as $field => $value) {
#create an object that becomes later {name:'abc',percent:'12'}
$obj = new stdClass();
$obj->name = $field;
$obj->percent=$value;
#collect it in the array,
#it becomes lates [{name:'abc',percent:'12'},{...},{...}]
$datasets[] = $obj;
}
#parse the data into the javascript part of the html content
?>
var datasets = <?php print json_encode($datasets);?>;
<?php
Hopefully, you can work with this.

If this is the real code you are using then the first bit of PHP consumes all of the resultset held in $result therefore there is nothing returned in the second bit of PHP
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
// $result has already been fully consumed
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
];

Related

How to store MySQL date in Javascript array?

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>

Real-time updation of C3.js -- fetching from DB?

What I'm doing:
Fetching data of tweets from MySQL using PHP; assigning the PHP output to a Javascript array; passing the JS array as a parameter to C3.js.
Problem:
The MySQL DB is constantly updated. So I need to update the C3 graph as well. My problem is that I'm mixing PHP and JS, so I'm not able to bundle them into the same function and call this function. How can I fetch the fresh data from the DB and update the graph?
Here's the code:
<?php
// Fetch data from DB
$sql = "SELECT created_at, COUNT(text) as tweetcounts from brexittweets group by created_at order by created_at desc limit 100";
$result = $conn->query($sql);
?>
<script>
var timeStamps = [];
var statusesCount = [];
timeStamps.push('timeStamps');
statusesCount.push('statuses');
<?php
if ($result->num_rows > 0) {
// assign PHP output to JS variables
while($row = $result->fetch_assoc()) { ?>
timeStamps.push('<?php echo $row['created_at'];?>');
statusesCount.push('<?php echo $row['tweetcounts'] ?>');
console.log(timeStamps);
<?php
}
} else {
echo "0 results";
}
?>
</script>
<?php echo '<div id ="chart2"></div>'?>
<script>
var chart = c3.generate({
bindto: '#chart2',
data: {
x: 'timeStamps',
xFormat: '%Y-%m-%d %H:%M:%S',
columns: [
timeStamps,
statusesCount
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format:'%H:%M:%S'
}
}
}
});
setTimeout(function () {
// Need to fetch fresh data here
}

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

Generate Markers from Mysql Database

I have an array of markers coded into a web page and I use them to generate markers for a google map in the form of
generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]);
So now am attempting to retrieve marker positions from a database so I attempted to use the code below to do so
getmkrs(
<?php
$db_con = mysql_connect("localhost",'root','');
mysql_select_db("db_name",$db_con);
$query_db = "Select * From table_name";
$result = mysql_query($query_db, $db_con);
$joiner = '';
?>
var_markers = [<?php while($row = mysql_fetch_assoc($result)):?>
<?= $joiner ?>
[<?= $addslashes($row['Row1']) ?>, <?= $row['Row2'] ?>, <?= $row['Row3'] ?> ]
<?$joiner = ','?>
<?php endwhile; ?>];
);
But Ultimately the page turns up blank, not even the map shows up. I am trying to replicate the above array which I coded into the web page. So my question is how can I efficient generate markers using data from a databse
For the love of god, don't cobble together JSON by hand interspersed in Javascript code. Create a sane data structure in PHP and encode it using json_encode:
<?php
$db_con = mysql_connect("localhost", 'root', '');
mysql_select_db("db_name", $db_con);
$query_db = "SELECT * FROM table_name";
$result = mysql_query($query_db, $db_con);
$markers = array();
while ($row = mysql_fetch_assoc($result)) {
$markers[] = array($row['Row1'], $row['Row2'], $row['Row3']);
}
?>
<script>
var markers = <?php echo json_encode($markers); ?>;
generateMarkers(markers);
</script>

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.

Categories