I have a small problem. I would like to insert SQL table information into a predefined Javascript code. I know how it works with PHP but I have never done it with Javascript and so I need your help.
I am a total beginner.
SQL Table:
Date_begin | Date_end | Text
-----------|----------|-----
03/2002 |07/2020 |test1
05/2002 |08/2020 |test2
... |... |...
PHP SQL Query (PDO):
<?php
$Date_begin = $connection->query("SELECT Date_begin FROM `test_table`");
$Date_end = $connection->query("SELECT Date_end FROM `test_table`");
$Text = $connection->query("SELECT Text FROM `test_table`");
?>
Predefined static JavaScript Code where the Information must be put in:
<script>
['03/2002', '07/2020', 'test1'],
['05/2002', '08/2020', 'test2'],
....
</script>
My attempt to solve it to make it dynamic:
<script>
var Date_begin = <?php echo $Date_begin ?>;
var Date_end = <?php echo $Date_end ?>;
var Text = <?php echo $Text ?>;
begin loop
['XXX', 'XXX', 'XXX'], // SQL Row 1
['XXX', 'XXX', 'XXX'], // SQL Row 2
['XXX', 'XXX', 'XXX'], // SQL Row 3
... // SQL Row n
end loop
</script>
Now I need to generate the above lines dynamic and fill it with the SQL Information. I think I need a loop but I don't know the syntax. I also don't know if I passed the variables from PHP to JavaScript correctly.
Thanks for any help and answer.
At the moment, you are not fetching any data, just executing the queries. Note that you only need one query since you are fetching all the data from the same table with the same conditions (in this case, none). You can get a JavaScript array of data directly from your PHP code by using json_encode.
Your code should look something like this:
<?php
$result = $connection->query("SELECT Date_begin, Date_end, Text FROM `test_table`");
if (!$result) {
// deal with error
}
$data = $result->fetchALL(PDO::FETCH_NUM);
?>
<script>
var data = <?php echo json_encode($data, JSON_UNESCAPED_SLASHES); ?>
// process data array
</script>
Related
I have this PHP code:
$number = mysqli_num_rows(mysqli_query($db_conn, "Select * from barangay"));
for ($i=1; $i<=$number; $i++){
$chart_fetch=mysqli_query($db_conn, "Select * from health where BRGY_id=$i");
$chart_data[$i] = "";
while($chart=mysqli_fetch_array($chart_fetch)){
$chart_data[$i] .= "{year:'".$chart["year"]."', pneumonia:".$chart["pneumonia"].", asthma:".$chart["asthma"].", tuberculosis:".$chart["tuberculosis"]."}, ";
}
$chart_data[$i] = substr($chart_data[$i], 0, -2);
}
and for the chart script:
<script>
var max = <?php echo $number; ?>;
for (i=1; i<=max; i++){
Morris.Bar({
element: 'chart'+i,
data:[ <?php echo $chart_data[$i]; ?>],
xkey:'year',
ykeys:['pneumonia', 'asthma', 'tuberculosis'],
labels:['Pneumonia', 'Asthma', 'Tuberculosis'], //label for the pop-up key
hideHover:'auto',
barColors: ['#036016', '#009f29', '#03440C']
});
}
</script>
I can't seem to get the chart_data[$i] to keep on adding one value so that i could get the fetched data from the php script as I had stated above.
The output of my codes must look like this:
For Barangay 1
For Barangay 2
Because I cannot create loop or concatenate the script variable i to the php code because of the client and server issue.
I already got the answer to my problem. All I have to do was just to insert the script inside the php code, and let php do the looping for me.
I should have known it sooner. :)
But anyway, here's the code to help others with cases such as this.
<?php
$number1 = mysqli_num_rows(mysqli_query($db_conn, "Select * from barangay"));
for ($z=1; $z<=$number1; $z++){
$z=$z;
echo"<script>
var i =1;
var max= $number1;
Morris.Bar({
element: chart$z,
data:[$chart_data[$z]],
xkey:'year',
ykeys:['pneumonia', 'asthma', 'tuberculosis'],
labels:['Pneumonia', 'Asthma', 'Tuberculosis'],
hideHover:'auto',
barColors: ['#036016', '#009f29', '#03440C']
});
</script>
";
}
?>
And the output would be different bar graphs which are getting their data from the database. <3 Like this, (this is from a 67% zoom from my web browser so you could see 2 of my 7 graphs having different data fetched from the database):
Bar Graph 1 and 2
I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>
I have the following issue, my php code gets the required data from the dB:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
As you see this writes to a json file - results:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
When I use the following js code to extract from json file:
$.getJSON('newport.json', function(data) {
console.log(data);
The console log using chrome displays the following:
[Object]
0: Object
nmech: "3.00"
__proto__: Object
length: 1
only shows the first key/value pair and not all 4 K/V pair? Can someone explain what I am doing wrong please.
Writing the results to a json file is overkill, IMHO. Why not just add the json into a Template or Page view (PHP).
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? #json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
Obviously, you don't have a Registration namespace object, but this just an example approach to setting settings from PHP when the page first loads.
All you really need it to output some data.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : json_encode(array()); ?>;
</script>
Or maybe a more simple way to write it would be.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : '[]'; ?>;
</script>
I can see your trying to file (or cache) the results. You should probably just write an AJAX method in your PHP controller to handle the request. The data could be cached server side in Memcached or some other fast handler of data. Most PHP frameworks support memcached.
This is ok, because your PHP array looks like this:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
You must use data[0]['key'] to access key1 part of first element.
Another (better solution) is to not to use while loop in php, since you are expecting 1 element in your case to be returned from mysql. Use like this then:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
Now your data will be in javascript like you expected on beginning.
I'm trying to automate my textfield of webform with auto search from database, where I have been trying it from many days. What I see is I get all the data which I typed but not with the data in the database. Can anyone help me out of this?
<script>
$(document).ready(function(){
$('input.module_nbr').module_nbr({
name: 'module_nbr',
remote:'search.php?key=%QUERY',
limit : 3
});
});
</script>
<?php
$key=$_GET['key'];
$array = array();
$dbc = mysqli_connect('','', '', '') OR die(mysqli_connect_error());
date_default_timezone_set("Asia/Calcutta");
$query=mysqli_query("select module_nbr from module_master where module_nbr LIKE '%{$key}%'");
while($row=mysqli_fetch_assoc($query));
{
$array[] = $row['module_nbr'];
}
echo json_encode($array);
?>
This will be a piece of code where I'm going to implement it in almost all fields of my form to reduce typing to the user.
I have functions stored in SQL table that I need to use inside JS. The problem is, that I also need to use PHP variables in these functions.
The following:
<?php
$container='11';
$title='Header';
$function_text =
<<<EOT
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
EOT;
echo $function_text;
?>
returns correctly:
$(function() {
$('#container11').parent('div').find('h3').html('Header');
});
but this one:
<?php
$ID=1;
$container='11';
$title='Header';
$article = $cls -> Query(sprintf('SELECT * from graphs WHERE ID="%s"', $ID));
$function_text = $article[0]['function'];
echo $function_text;
?>
prints exactly the contents of SQL field, without recognising variables:
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
How could I get the variables to be injected to echoed text?
Change the data that is stored in your database, so that it uses format placeholders instead of references to variables:
$(function() {
$('#container%s').parent('div').find('h3').html('%s');
});
Use sprintf():
$function_text = sprintf($article[0]['function'], $container, $title);