我有一个搜索栏,可以返回我的成员表中的用户名。然而,不仅仅是显示他们的用户名,我希望结果能够链接到他们各自的个人资料。
以下是搜索栏的PHP代码:
<?php
$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);
}
$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ?
LIMIT 3");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
echo $username;
echo "<div>".$searchResults."</div>";
}
?>
这是实际的搜索栏,其中结果div是ajax的目标div:
<li><input type="text" name="partialSearch"onkeyup="search(this.value)" placeholder="Search for other users"/></li>
<section id="divider">
<div id="results"></div>
AJAX:
function search(partialSearch){
$.ajax({url:"searchbar.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){
$("#results").html(result);
}});
};
以下是我用于生成用户个人资料的代码:
<?php
function user_profile(){
$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;';
$result = $conn->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
$user[]= $row;
}
return $user;
foreach (user_profile() as $user){
?>
<p>
<a href="ViewProfile.php?uid=<?php echo $user['memberID'];?>"><?php echo $user['username'];?></a>
</p>
<?php
}
}
?>
提前感谢您的帮助。希望得到意见和建议
答案 0 :(得分:0)
你非常接近完成申请。我重构了您的代码,并添加了详细的注释以指导您完成更改。
搜索页面
<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");
&#39;%&#39;还将包含以搜索值开头的用户名。
<强>第二强>
在同一文件中,未定义$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>";
}