mySQLi to Json to Js file - javascript

Hello I am trying to output my mysqli database to a js file after encoding it, I have no trouble encoding it with json_encode but how can I get it into a js file (updating every time the mysqli data is updated)
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM tablename")) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
Any help or insight would be great! thanks

To return a json file you will have to set json headers at the top of your PHP code:
header('Content-Type: application/json');
If you just want to write the json code into an external file you would have to use PHPs fwrite().
However you can't automatically update the file, when the database is updated. You need to call your PHP file in order to update the json file.
Maybe you can solve this by using a MySQL trigger in your database, more information here.

Related

Customize query not working in Wordpress page?

This is page of wordpress I am adding core php code for displaying data into table as per select input for that I am using javascript for gettin input and pass to the page page.And that page getting value as per value fir a mysql query.But my core php code dispaly as it is on screen. I am not able to understand how to do this. Beacuse I am new in wordpress Today is my first day in wordpress. Please help me ..Thanks in advance
<?php
$var=$_COOKIE['v'];
$id = explode(",", $var);
echo 'hawno:'.$id[1];
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("shepherddb");
$err = error_reporting(E_ALL && ~E_NOTICE);
$result=mysql_query("select ship_id,track_id,track_ship_id,track_mod_of_transport,track_location,track_status from
tracking,shipment");
while($data = mysql_fetch_array($result)) {
print_r($data);
}
?>
You need to use $wpdb global object provided by wordpress.
For example ,
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
You can also use pre_get_posts action to modify the POSTS Query.
add_action( 'pre_get_posts', 'your_theme_function' );
Let me know if you need more information on the same.

Improve Page Performance, save PHP array on server?

is it possible to store a PHP-array to my server, right now it always gets created when someone reloads the page from a CSV file but that is unnecessary since the file only chances after each hour.
ATM, the page takes like 9 seconds to load, which is quite long. The CSV file has 10k+ rows with 9 elements per row, so it would be really good for performance if the server didn't have to process 100k elements for each user.
I already have a cronjob for downloading the csv file so it would be good if the parse command would be executed after the download finished, only once per hour.
cronjob:
<?php
function download_remote_file($file_url, $save_to) {
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
download_remote_file(<url here>, realpath(".") . '/dump.csv');
?>
and this happens with every reload of the page:
1st: Parse data to array
$url = 'dump.csv';
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$line = str_replace("\\", "\", $line);
$line = str_replace("#", "#", $line);
$array[] = str_getcsv($line);
2nd: pass array to Javascript
var array = <?php echo json_encode( $array ) ?>;
3rd: create HTML table
//some code
4th: initialise data table plugin
$(document).ready( function () {
createtable();
$('#scoreboard').DataTable( {
"iDisplayLength": 50,
language: {
decimal: ".",
},
"lengthMenu": false,
"bLengthChange": false
} );
} );
Is there something that could be done faster?
Like, as mentioned, save the php array server-side or maybe saving the JS array with the HTML table somehow?
-Innerwolf
After you parse your CSV, do this:
$file = fopen('/tmp/output.js', 'w');
fwrite($file, '<script type="text/javascript">');
fwrite($file, 'var array =');
fwrite($file, json_encode( $array ));
fwrite($file, ';');
fwrite($file, '</script>');
fclose($file);
copy('/path/to/script.js', '/path/to/script.js.bak');
move('/tmp/output.js', '/path/to/script.js');
Then, later on when you are outputting the HTML, you just need to stick in a:
<script type="text/javascript" src="/scripts/script.js">
in the header. People's browsers should cache it properly too. Note the copy and move -- you don't strictly need to make a backup copy, but you MUST use a move() to replace the 'live' script -- move() is atomic, more or less, and won't result in anyone getting a half-file.
Also, note that you'll need write permissions to where the script is -- there are ways to keep this pretty secure (not letting your PHP script write all over the hard drive), but that's out of scope here.
Since you mention getting the data on an hourly basis I suggest the following:
grab the CSV file with cron and store the data in a database on an hourly basis
configure your data tables component to use server side data
This way you won't force every user to download the entire array at once on every first page load.
The server side script only fetches the number of records that need to be displayed on that particular page in the table.

Pass parameters to PHP and build query

I'm trying to get PHP code like this to work:
<?php
$hostname = '******';
$database = 'firstdb';
$username = '*****';
$password = '*****';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sortvalue = "datbase_percent";
$sortorder = "ASC";
$sql = "select * from advanced_data where category like age_group order by {$sortvalue} {$sortorder};";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
?>
What I want to be able to do is define the $sortvalue and $sortorder via an AJAX call. I'm getting it now like this:
$.getJSON('all_get_2.php', function(data) {
Two questions...my PHP code doesn't work because I can't figure out the proper syntax for building the $sql variable the makes up the mySQL query. I've tried a bunch of things, but keep getting 500 errors. If I just type in the values, then the code works, so I know it's just a problem with my syntax.
Second question...what's the best way to pass a variable into $sortvalue and $sortorder from my front end? I know it's something using $.ajax, but not sure of the best way to do it. The idea is that the user would click a button, which corresponds with sorting a chart ascending or descending and reloads the chart without reloading the page. Any direction here would be appreciated.

URL in database to Javascript with PHP

I've added a table in my mySQL database which has two variables: ID and a URL.
ID has the value 1
and
URL has http://www.examplesite.com
I want to get "www examplesite com" from the database into a PHP file.
The PHP file should then send this string to a javascript file which will then open that URL.
So far I've been using getJSON with little success.
I'm new to PHP and Java and would really appreciate some help!
I want something like this in my .js file
$.getJSON('getlink.php', {'link'}, function(e) {
alert('Result from PHP: ' + e.result);
});
window.open(linkVariable'_blank')
I would like linkVariable to be www examplesite com
The javascript is linked to another php file which has a clickable element for the window.open.
How can I get the getlink.php and the .js file to communicate with each other?
EDIT:
My getlink.php would look something like this without any echo. The connection to mySQL is already written.
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res['URL'];
it would be better if you posted what code is in getlink.php.
I'd suggest you proceed like this. In getlink.php query the database to return the correct row.
There is different ways to do that, depending on what framework or library (PDO,mysql_,) you are using.
Then return the result as json
In the same file, call the function you just defined.
It should look to something like this
<?php
function get_links($url_link) {
$sql = "SELECT `name` FROM `variables` WHERE ID=?";
$res = $this->db->query($sql, array($url_link))->row_array();
return $res;
}
$result = get_links(1); //whatever the id is
return json_encode($result);
?>
In your javascrit you can do something like this
$.get(
"getlink.php",
function(data) {
alert(data.URL);
}
);
//My Idea
Read URL from the database and give it to the variable $link code below
$result=mysqli_query($dbconnection, "SELECT * FROM url"); //You can specify conditions
while($row=mysqli_fetch_array($result)){
$link=$row["URL"]; //We have our url from database here
}
//Link between JAVASCRIPT AND PHP
Put this code in a php to take $link and give it to getlink() function as a parameter
<script>
getlink("<?php echo $link?>"); //A java script function from your JS file to get url
</script>

Is json_encode extremely picky?

It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!

Categories

Resources