gpt4 book ai didi

php - 通过 PHP 进行 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 07:24:08 24 4
gpt4 key购买 nike

我一直在从事一个 SQL 项目。我有一个包含两列的表格,以及一个搜索功能,要求用户以简单的形式输入用户名。然后我的 php 脚本会回显与该用户名关联的全名。

这是包含表单的 HTML 页面:

<html> 
<head>
<title>Search Contacts</title>
</head>
<p><body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="search.php" id="searchform">
<input type="text" name="username">
<input type="submit" name="submit" value="Search">
</form>
</body>

这是与全名相呼应的 php 脚本:

<?php
$con=mysqli_connect("localhost","root","hidden","users");

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=['username']
$sql="SELECT * FROM `users` WHERE `user` LIKE $username";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$username =$fieldinfo ['username'];
}

// Free result set
echo $username;
}
mysqli_close($con);
?>

最佳答案

用户名是一个字符串,因此需要用引号引起来。

您还缺少分配给 $username 的行上的分号,并且您分配的值应为 $_POST['username']

如果查询失败,您应该显示包含失败原因的错误消息。

您只是回显最后一个匹配的用户名。您应该将 echo 语句移到循环内。

要对名称中包含 $username 的任何用户进行 LIKE 搜索,您需要在所使用的搜索字符串周围放置通配符 % 字符与LIKE

<?php
$con=mysqli_connect("localhost","root","hidden","users");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=$_POST['username'];
$sql="SELECT * FROM `users` WHERE `user` LIKE '%$username%'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$username =$fieldinfo ['username'];
echo $username;
}
}
else
{
die(mysqli_error($con));
}
mysqli_close($con);
?>

但是如果您学会使用准备好的查询会更好。这是用这种风格重写的代码。

<?php
$con=mysqli_connect("localhost","root","hidden","users");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=$_POST['username'];
$sql="SELECT username FROM `users` WHERE `user` LIKE CONCAT('%', ?, '%')";
$stmt = mysqli_prepare($con, $sql);
mysql_bind_param($stmt, "s", $username);
if ($result=mysqli_execute($stmt))
{
mysqli_bind_result($stmt, $username);
// Get field information for all fields
while (mysql_fetch($stmt)) {
echo $username;
}
}
else
{
echo mysqli_error($con);
}

mysqli_close($con);
?>

关于php - 通过 PHP 进行 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com