【问题标题】:Dynamically show SQL query on a PHP page on click, using AJAX点击时在 PHP 页面上动态显示 SQL 查询,使用 AJAX
【发布时间】:2015-04-12 07:03:19
【问题描述】:

基本上,我想在点击一个元素后检索某个产品。我使用 AJAX 传递变量,使用 PHP 显示 SQL 查询。我将在 WHERE 语句中使用产品 ID 来检索和显示正确的产品。

到目前为止,这是我的部分代码:

<html>
<head>
    <title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>

<body>
<div class="container">

    <div id="bottomHalf">
        <img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
        <img src="assets/frosen_food.png"
        usemap="#Map2"
        border="0"
        id="frozen"
        style="z-index: 0;
        visibility:hidden;" >

        <map name="Map2">
            <area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">

     </div>
</div>
<script language="javascript">

  $("#hamburgerPatties").click(function(){
         var hamburgerPatties = "1002";
      $.ajax({
          type:"GET",
          url: "topRightFrame.php",
          data: "variable1=" + encodeURIComponent(hamburgerPatties),
          success: function(){
          //display something if it succeeds
          alert( hamburgerPatties );
      }
      });
  });

</script>
</body>
</html>

我的部分 PHP 代码:

<?php

$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);

// Display all products on the database
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
    }
} else {
    echo "0 results";
}

    // Display product I clicked on the other frame
    if (isset($GET['variable1'])) {

    $sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
    $result = $conn->query($sql);

        if ($result) {
        echo '<table>';

            while ($row = $result->fetch_assoc())
            {
            echo '<tr>';
            echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
            echo '</tr>';
            }
        echo '</table>';
        }
}
$conn->close();
?>

我可以展示所有产品。但是从 ifsset 语句开始,代码不再起作用。我没有收到任何错误消息或任何东西。我该如何解决这个问题?我对 PHP 很陌生。

编辑:好的,当我对产品 ID 进行硬编码时,我设法得到了我想要的产品。现在我需要使用 javascript 来获取这个变量。

【问题讨论】:

    标签: javascript php jquery mysql ajax


    【解决方案1】:

    您的if 语句中有语法错误。

    在设置if 时,应将语句括在大括号中:

    if(something): 代替if something :,然后以endif; 结束(使用冒号 :

    // Display product I clicked on the other frame
    if (isset($GET['variable1'])):
        $query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
        $result = mysqli_query($conn, $query);
        if ($result):
            echo '<table>';
            while ($row = $result->fetch_assoc()) {
                echo '<tr>';
                echo '<td>', $row['product_id'], '</td>'; // and others
                echo '</tr>';
            }
            echo '</table>';
        endif;
    endif;
    

    或者,使用{} 大括号代替冒号 :

    // Display product I clicked on the other frame
    if (isset($GET['variable1'])){
        $query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
        $result = mysqli_query($conn, $query);
        if ($result){
            echo '<table>';
            while ($row = $result->fetch_assoc()) {
                echo '<tr>';
                echo '<td>', $row['product_id'], '</td>'; // and others
                echo '</tr>';
            }
            echo '</table>';
        }
    }
    

    【讨论】:

    • 改变了这些,我改变了一些其他的东西,但仍然不行。
    • 你没有仔细阅读我的回答。你还有 if isset($GET['variable1']) { 。您也应该用 () 大括号括住 isset,例如 if (isset($GET['variable1'])) {
    • 抱歉,我没有注意到。现在代码正在运行,它显示了所有数据,但单击产品元素后什么也没有。
    • 我在您的代码中没有看到任何 product 元素。您问题中的 PHP 是什么,它是 topRightFrame.php 文件的一部分吗?控制台会说什么吗?
    • 更新了代码,本例中的产品元素是汉堡包。是的,是 topRIghtFrame.php 文件。我的控制台上没有错误。
    【解决方案2】:

    if 块中有语法错误。将 {} 用于 if 块也使用 echo 而不是纯 html 标记(表)。此错误会阻止 ajax 请求的成功状态。也不要忘记关闭表。

    if ($result)
    {
     echo '<table>';
    
     while ($row = $result->fetch_assoc()) 
       {
        echo '<tr>';
        echo '<td>', $row['product_id'], '</td><td>'; // and others
        echo '</tr>';
    
      }
     echo '</table>';
    }
    

    显示 php 结果而不是测试警报的 ajax 代码是这样的:

    <script language="javascript">
    
      $("#hamburgerPatties").click(function(){
             var hamburgerPatties = "1002";
          $.ajax({
              type:"GET",
              url: "topRightFrame.php",
              data: "variable1=" + encodeURIComponent(hamburgerPatties),
              success: function(data){
              alert(data);
          }
          });
      });
    
    </script>
    

    【讨论】:

    • 如果在传递variable1作为查询字符串时直接打开php页面会发生什么?
    • 当我对 ID 进行硬编码时,我设法检索到我想要的产品。编辑了工作代码。现在我需要能够使用 ajax 来检索这个值,而不是手动输入它。
    • 好的!我已经更新了答案,包括 jquery 以显示数据而不是假警报。
    • 当我这样做时,我会收到一条警报,显示我的 PHP 页面的源代码。这是我应该期待的输出吗?如果我添加 echo $product_id,我会在此警报中获得正确的产品。但是,PHP 页面仍然没有任何反应,它保持静态,并且 SQL 查询没有运行。
    • 如果将 variable1 转换为 number 以确保 sql 查询中没有数据类型问题,该怎么办。我的意思是:其中 productId=".intval($_GET['variable1'])
    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2018-06-20
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多