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>
Related
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>
I'm using the autocomplete UI for my search box. Below is my php code:
<?php
include 'connect.php';
if (isset($_GET['term'])) {
$value = $_GET['term'] . '%';
$return_arr = array();
$stmt = $conn->prepare("SELECT * FROM jobs WHERE jobname LIKE ? or formtype LIKE ?");
$stmt->bind_param("ss", $value, $value);
$stmt->execute();
$stmt->bind_result($entryid, $jobnumber, $jobname, $formtype, $date);
while ($stmt->fetch()) {
$return_arr[] = $jobname;
$return_arr[] = $formtype;
}
echo json_encode($return_arr);
}
?>
Everything works perfectly fine. But I kind of want for the while statement to return all $jobname values first before the $formtype values. In short, I want the values to be returned by column and not by row. I'm not sure how it is possible because I tried putting them inside do while and foreach statements but both didn't work for me.
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
. But I kind of want for the while statement to return all $jobname values first before the $formtype values.
Build two arrays and then merge them:
$ar1 = [];
$ar2 = [];
while($stmt->fetch()) {
$arr1[] = $jobname;
$arr2[] = $formtype;
}
$return_arr = array_merge($arr1, $arr2);
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
Because autocomplete expects json object and you want to try give him json object and something else
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 sending array from Php to Javascript, then I try to generate a div for each value of that array to display them in html, but instead of making a div for each independent value it stacks them all on a single one. It seems the array I'm making in php arranges all the values from my database into single string.
How can I separate them?
Here's how the error looks upfront
Here's part of my code:
Php:
$query= "SELECT titulo FROM notas WHERE usuario_idusuario = '".$ide."'";
//Runs the search
$resultado = $conn->query($query);
if($resultado->num_rows>0){
while($row = $resultado->fetch_assoc()){
//inserts result in an array
$contenido= array('titulo'=> $row['titulo']);
//json_encode
$objJson = json_encode($contenido["titulo"]);
//sends the array to javascript
echo "$objJson\n";
}
}else{
echo "Error";
}
$conn->close();
?>
javascript:
//response receives the array
success: function(response){
console.log(response);
console.log(response.length);
var contenidoInt = new Array();
contenidoInt = [{
"titulo":response
}];
console.log(contenidoInt);
console.log(contenidoInt[0].titulo);
}
I hope someone can help me, thanks.
Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});