【问题标题】:Selecting and retrieving Data from a MySQL Database using PHP and AJAX使用 PHP 和 AJAX 从 MySQL 数据库中选择和检索数据
【发布时间】:2016-11-07 22:26:38
【问题描述】:

我正在尝试从托管在网络服务器上的 MySQL 数据库中选择数据。我希望能够从数据库中的表中检索数据,然后在 HTML 表中对其进行说明。我一直在关注 W3Schools 上的一个示例,但我无法成功检索数据。

以下是源代码:(HTML)

<html>
<head>
//Javascript code
<script>
       function showUser(str) {
           if (str == "") {
               document.getElementById("txtHint").innerHTML = "";
               return;
       } else { 
           if (window.XMLHttpRequest) {
           // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp = new XMLHttpRequest();
      } else {
          //  code for IE6, IE5
              xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
     };
       xmlhttp.open("GET","getuser.php?q="+str,true);
       xmlhttp.send();
 }
}
</script>

</head>
<body>

<form>
 <select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

PHP 文件:(getuser.phd)

<!DOCTYPE html>
<html>
<head>
<style>
  table            {
  width: 100%;
  border-collapse: collapse;
        }

     table, td, th {
            border: 1px solid black;
            padding: 5px;
        }

     th {text-align: left;}
</style>
</head>
<body>

<?php
     $q = intval($_GET['q']);

$con = mysqli_connect(‘www.example.com’,’user_Admin’,’12345-678’,’my_DB');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

  echo "<table>
<tr>
 <th>Firstname</th>
 <th>Lastname</th>
 <th>Age</th>
 <th>Hometown</th>
 <th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
}
  echo "</table>";
  mysqli_close($con);
?>
</body>
</html>

我认为问题可能从 PHP 文件中的 mysqli_select_db($con,"ajax_demo"); 开始存在。我应该指的是包含数据库内数据的表吗?

我的网络服务器上托管了 PHP 文件,所以我不确定为什么当从 HTML 页面上的选项列表中选择一个人时它不会检索该数据。

任何帮助将不胜感激。

【问题讨论】:

标签: javascript php html mysql ajax


【解决方案1】:
mysqli_select_db($con,"ajax_demo");

"ajax_demo" 替换为您的数据库名称。

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 2017-12-05
    • 1970-01-01
    • 2014-05-03
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2020-01-13
    相关资源
    最近更新 更多