您已经非常接近完成申请了。我重构了您的代码,并添加了详细的注释来指导您完成更改。
搜索页面
<form action="#">
<input type="text" name="partialSearch" onkeyup="search(this.value)" placeholder="Search for other users"/>
</form>
<section id="divider">
<div id="results"></div>
</section>
<!-- always place scripts just before the ending <body> tag for better performance -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function search(partialSearch) {
$.ajax({
url: "search_results_ajax.php",
type: "POST",
data: {partialSearch: partialSearch},
success: function (result) {
$("#results").html(result);
}
});
}
</script>
Ajax 搜索
<?php
/**
* Your function names should match their purpose. user_profile() does not accurately define the operations
* this function will be performing.
*
* @param array $usernameToSearch - The username to compare with the database.
*
* @return array - A list of users.
*/
function get_users_by_username($usernameToSearch)
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/**
* The query below will fetch all of your users from the database.
*
* SELECT memberID, username FROM members
*
* You can narrow the results by using the WHERE clause with the LIKE operator:
*
* $sql = 'SELECT memberID, username FROM members WHERE username LIKE "%' . $username . '%"'
*
* Learn more about the LIKE clause at: http://www.w3schools.com/sql/sql_like.asp
*/
$sql = 'SELECT memberID, username FROM members WHERE username LIKE "%' . $usernameToSearch . '%"';
$result = $conn->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
/** Renamed from $user to $users to match variable definition. */
$users[] = $row;
}
/** Renamed from $user to $users to match variable definition. */
return $users;
}
/**
* Your AJAX request sends a parameter called "partialSearch", which contains the value of the textbox
* on the search page. You can access that parameter through the PHP global, $_POST.
*
* (or $_GET, if the parameter is stored in the url. Such as: www.mywebsite.com?partialSearch=my+search+here)
*
* Before you execute get_users_by_username(), you must check if the "partialSearch" parameter exists. This
* can be done through the empty() function, which essentially checks if the value if $_POST['partialSearch'] is:
* - false
* - an empty string
* - null
*
* The NOT operator "!" in front of empty() will flip the value returned by empty(). So if empty() returns true, the
* NOT operator will flip it to false. This important because we only what the code within the "if" statement to
* execute if $_POST['partialSearch'] is NOT empty.
*/
if(!empty($_POST['partialSearch'])) {
/** Store the results of get_users_by_username(), so we can count the number of results without re-running the function. */
$users = get_users_by_username($_POST['partialSearch']);
/**
* Foreach loops with through warnings if user_profile() returns an empty value. Make sure count($users) is > 0
* before running the loop.
*/
if(count($users) > 0) {
foreach($users as $user) {
print '<p>
<a href="ViewProfile.php?uid=' . $user['memberID'] . '">
' . $user['username'] . '
</a>
</p>';
}
} else {
print "<p>No Results</p>";
}
}
/**
* In files with only PHP code, you do not need the closing PHP tag.
*
* "?>"
*/
用户个人资料
<?php
/**
* Fetch user from database by their memberID.
*
* @param $id - The user's ID
*
* @return array - The user database record.
*/
function get_single_user_by_id($id)
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT memberID, username FROM members WHERE memberID = ' . $id;
$result = $conn->query($sql);
//Return single user
return $result->fetch_assoc();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Demo</title>
</head>
<body>
<?php
if(!empty($_GET['uid'])) {
$user = get_single_user_by_id($_GET['uid']);
if(!empty($user)) {
print "<h1>Welcome " . $user['username'] . "!";
} else {
print "User with ID " . $_GET['uid'] . " doesn't exist.";
}
} else {
//No UID was provided
print "Please provide a UID to a valid user.";
}
?>
</body>
</html>
提示 1
不要在应用程序中使用mysql 或mysqli 数据库连接。这两个连接都已被弃用,并且非常不安全。查看this 和this 了解SQL 注入攻击。为防止此类攻击,请使用PHP Data Objects (PDO)。
提示 2
在另一个文件中定义您的函数,与您的 HTML 分开。将函数定义放在 HTML 旁边会很快变得混乱。您可以使用 PHP 的 include 和 require 函数来执行此操作。 (learn about it here)
提示 3
使用重复代码通常是不好的做法。您正在使用相同的代码在两个页面(搜索 ajax 和配置文件页面)上连接到您的数据库。我建议构建一个数据库类来处理应用程序的所有数据库事务,这样您就没有重复的代码。 This will help you with that.
更新
您的搜索栏 PHP 代码存在几个问题:
第一
您的代码中的以下行只会获取完全匹配:
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ?
LIMIT 3");
为了实现您想要的自动完成搜索,您需要为其添加通配符:
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE '?%' LIMIT 3");
“%”还将包括以搜索值开头的用户名。
第二
在同一个文件中,$searchResults 变量未定义。您的结果字符串将始终为空。
您需要更改循环遍历结果并为每个结果打印一个链接。
while ($stmt->fetch()) {
echo $username;
echo "<div>".$searchResults."</div>";
}
到:
$results = $stmt->fetchAll();
if($results > 0) {
foreach($results as $user) {
print '<p>
<a href="ViewProfile.php?uid=' . $user['memberID'] . '">
' . $user['username'] . '
</a>
</p>';
}
} else {
print "<p>No Results</p>";
}