php/mysql write array to json file - javascript

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.

Related

Importing MySQL Table in predefined Javascript Code

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>

Return data from PHP to JavaScript using AJAX - data type error?

I am using AJAX to return a query to my JavaScript function, but I am having an issue returning the json_encode. I might have an error in the data type somewhere, but thought to check here for some advice.
This is my AJAX request:
$.ajax({
url: 'testajax.php',
method: 'POST',
data: {value},
dataType:'json',
success: function(data){
console.log(data);}
});
This is my PHP script:
<?php
require 'login.php';
$connection = new mysqli($host, $user, $pword, $database, 3306);
$insertquery = $connection->prepare("SELECT tracking_type, tracking_change_date, vessel_fcm_new, vessel_hull_id_new, vessel_name_new, vessel_length_new, vessel_manufacturer_new, vessel_manufacturer_id_new, vessel_year_new, vessel_value_new, owner_id_new, loss_payee_id_new, policy_id_new, policy_start_date_new, policy_end_date_new FROM tracking WHERE tracking_type = ?");
$insertquery->bind_param("i", $trackingtype);
//$trackingtype = $_POST['value'];
$trackingtype = 1;
$insertquery->execute();
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
echo json_encode($data);
}
If I only have 1 row matching this query, then it works fine. But as soon as I add another row that matches the select query, it does not return properly to the JavaScript function, but does display fine in the browser (if you visit testajax.php).
This is currently how the data is being returned. Maybe I have an error in the data type being usesd:
["Insert","2018-05-26","JBL5693",null,"Makers Mark","22","sdgfsg3","256632asdasd",2014,263,"217","11",null,null,null]["Insert","2018-05-27","fFH465","FDDEE453","GIIGE","22","Shippers","2432465we",2014,205222,"Smith Jones","Capital One",null,null,null]
This bit might have given you a clue If I only have 1 row matching this query, then it works fine
So save your rows in an array and then send the whole array like this
while ($insertquery->fetch()){
$data[] = array($tracking_type, $tracking_change_date, $vessel_fcm_new,
$vessel_hull_id_new, $vessel_name_new, $vessel_length_new,
$vessel_manufacturer_new, $vessel_manufacturer_id_new,
$vessel_year_new, $vessel_value_new, $owner_id_new,
$loss_payee_id_new, $policy_id_new, $policy_start_date_new,
$policy_end_date_new);
}
echo json_encode($data);
EDIT:
A simple test of this code would be
$data[] = array('Insert','2018-05-26', 1);
$data[] = array('Insert','2018-05-26', 2);
echo json_encode($data);
This will generate
[
["Insert","2018-05-26",1],
["Insert","2018-05-26",2]
]
and not the sample output you suggest.
The problem is that you're printing an array of columns for each pass through the loop and therefore the JSON is not be correctly encoded as an array of arrays; you can modify your code as follows:
$results = array();
while ($insertquery->fetch()) {
$newResult = array($tracking_type, $tracking_change_date, ...);
array_push($results, $newResult);
}
$encoded = json_encode($results);
echo $encoded;
Will print something like this:
[
["Insert","2018-05-26","JBL5693", ...],
["Insert","2018-05-27","JBL5694", ...],
...
]
Note that it's better to design a client<>server interface to use an array of objects, something like:
[
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
{"tracking_type": "Insert", "tracking_change_date": "2018-05-26", "vessel_fcm_new": "JBL5693", ...},
...
]
This approach has the advantage that the client client does not need to know the order of the columns, rather it can directly access the properties it cares about.
What you should be doing is return an array of objects. Not multiple objects.
$to_return = [];
while ($insertquery->fetch()){
$data = array($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_hull_id_new, $vessel_name_new, $vessel_length_new, $vessel_manufacturer_new, $vessel_manufacturer_id_new, $vessel_year_new, $vessel_value_new, $owner_id_new, $loss_payee_id_new, $policy_id_new, $policy_start_date_new, $policy_end_date_new);
$to_return[] = $data;
}
echo json_encode($to_return);
Make sure to keep
echo json_encode($data);
outside of the while loop.

How to return the elements of an array from my database into my php as Ajax links

Basically I have a database and I'm making a webpage with PHP.
I get a row of Elements from my database and put them into an array.
I need to display this array in my webpage, and the elements out of it have to be ajax links that display more information.
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$id = $row["name"];
$echo "$id";
This is my array where i have a list of names and i print it there, i want my prints to be links.
Any help? I'm pretty desperate
Make the datatype of AJAX call as JSON in the javascript and return a json encoded string from php. Then in the success block of the AJAX call , parse it by JSON.parse()
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$categoryDetails[] = $row;
}
echo json_encode( $categoryDetails );

JQuery GET request won't get correct data from php echo

I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test

How to insert a PHP 'while loop' into JavaScript code?

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>

Categories

Resources