使用Ajax PHP从数据库中获取动态选择的数据

时间:2018-07-25 20:57:14

标签: php html ajax mysqli

我的view.php页面来自另一个页面,通过获取唯一的ID(序列号)而来。现在,在我的view.php页面中,我想显示指定的序列,没有来自Charts.php的数据。我自己完成了代码。它正在获取数据。但不是那个选择的序列号。我该怎么解决

view.php

<?php 
if(isset($_GET['serial'])){
        $serial = $_GET['serial'];
?>
<html>
<div class="container" id="output"></div>
</html>
<script>
    $(document).ready(function(){
        function getData(){
            $.ajax({
                type: 'POST',
                url: 'charts.php',
                success: function(data){
                    $('#output').html(data);
                }
            });
        }
        getData();
        setInterval(function () {
            getData(); 
        }, 1000);  // it will refresh your data every 1 sec

    });
</script>

charts.php

<?php 
   $sql = mysqli_query($con,"SELECT * FROM criminal WHERE rand = '$serial'");
    while($row = mysqli_fetch_assoc($sql)){
 ?>

请帮助。

2 个答案:

答案 0 :(得分:2)

  1. 首先,如果(您忘记了}),请关闭第一个
  2. 在ajax中,在url行之后发送串行参数。 (data: {serial: "echo with php the variable"},
  3. 在Charts.php查询中,获取帖子值。 ($_POST['serial'])。

答案 1 :(得分:2)

您想将$ serial变量放在URL中。这称为查询字符串。

$(function() {
    function getData(){
            $.ajax({
                type: 'POST',
                dataType: 'JSON',
                url: 'charts.php?serial=<?= $serial?>', //<-- RIGHT HERE
                success: function(data){
                    $('#output').html(data);
                }
            });
        }
})

然后,您将获取刚从ajax发送的数据。它看起来像您的第一个GET变量。您将在查询中使用该变量。

在您的php中:

<?php 
   $your_variable = $_GET['serial'];
   $sql = mysqli_query($con,"SELECT * FROM criminal WHERE rand = '$your_variable'");
    while($row = mysqli_fetch_assoc($sql)){
        $variable_to_send = $row['serial']; //<--- Whatever your column name is
    }
    echo json_encode($variable_to_send);
 ?>

PDO版本 正如@JayBlanchard所建议的那样,强烈建议您对PDO进行一些研究。更安全。

我给你一个PDO示例:

$serial = $_GET['serial']; //The variable you're sending over from view.php

$hostname = 'your_hostname';
$username = 'your_username';
$password = 'your_passwd';
$dbname = 'your_db_name';

$pdo = new PDO("mysql:host=$hostname;$dbname=$dbname", $username, $password); //Create a new PDO object
$stmt = $pdo->prepare("SELECT * FROM criminal WHERE rand = :rand"); //prepare the query for execution
$stmt->bindValue(':rand', $serial); //bind your variable to your query
$stmt->execute(); //Run it
$result = $stmt->fetchColumn(); //Get a single column. No while loop.

echo json_encode($result); //Echo it back to your ajax function

我对照自己的数据库对此进行了测试,它在屏幕上显示的结果没有错误(当然使用了我自己的值)。

相关问题