如何从MYSQL中获取单个值并将其保存为JavaScript变量?

时间:2016-04-29 01:42:53

标签: javascript php mysql

我想选择表格的最后一行,并将所有值保存到单独的JavaScript变量中。我在PHP中使用了查询:

import java.util.Scanner; public class Project4JamesVincent { public static void main(String []args){ Scanner input = new Scanner(System.in); System.out.print("Enter the size of the arrays: "); int size = input.nextInt(); System.out.println(); System.out.println("Enter " + size + " items for array X: "); double[] arrayX = createArray(size, input); System.out.println(); System.out.println("Enter " + size + " items for array Y: "); double[] arrayY = createArray(size, input); System.out.print("The distance between x and y is: "); double totalDistance = 0; for (int i = 0; i<size; i++){ totalDistance = totalDistance + Math.abs((arrayX[i]-arrayY[i])); } double averageDistance = 0; averageDistance = (totalDistance/size); System.out.printf("%3.2f", averageDistance); } public static double[] createArray (int n, Scanner enter){ double[] tempArray = new double[n]; for (int i=0; i<tempArray.length; i++){ tempArray[i] = enter.nextDouble(); } return tempArray; } }

选择表格的最后一行。我不知道该怎么办。

2 个答案:

答案 0 :(得分:2)

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;
    });
});

答案 1 :(得分:0)

cookies方式绝对是要走的路。如果您在一个页面上完成所有这些操作,只需要快速修复即可

<?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>

这是一种懒惰的方式,很快就会变得混乱,但它对于理解PHP和JS如何协同工作非常有用