[英]How to take individual values from MYSQL and save it to a JavaScript variable?
I want to select the last row of my table, and save all the values to separate JavaScript variables. 我想选择表的最后一行,并将所有值保存到单独的JavaScript变量中。 I used the query in PHP: 我在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. 我不知道该如何进行。
PHP: 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: 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;
});
});
cookies way is definitely the way to go. Cookies方式绝对是必经之路。 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 这是一种懒惰的方法,很快就会变得混乱,但是对于理解PHP和JS的工作方式可能很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.