Reputation: 79
I want to select the last row of my table, and save all the values to separate JavaScript variables. I used the query in PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
to select the last row of the table. I don't know how to proceed.
Upvotes: 0
Views: 29
Reputation: 1187
cookies way is definitely the way to go. If you are doing all of this on one page and just need a quick fix you could do
<?php
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
$json_string = json_encode($row);
}
?>
<script> var sql_row = <?php echo $json_string; ?>; </script>
This is the lazy way and will get messy quickly, but it could be useful for understanding how PHP and JS work together
Upvotes: 0
Reputation: 333
PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
echo json_encode($row);
}
jQuery:
// sample variables
var username = "";
var password = "";
var phpUrl = 'http://sampleurl.com/mypage.php';
$.getJSON(phpUrl, function (result) {
$.each(result, function (data) {
// if data sent back is eg data:[{username:'sample', password:'sample'}]
// then you fetch and save as
username = data.username;
password = data.password;
});
});
Upvotes: 2