我有一个能够检索用户用户名的搜索表单,但我无法弄清楚如何让它返回更多,我希望它也能显示名字和姓氏。 / p>
以下是有效的分钟代码,但是当我尝试添加更多变量时,例如if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
,那么它根本不会返回任何内容并要求插入搜索查询。
我也尝试了if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%"))
和LIKE "%?%"))
,但没有结果。
的search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
答案 0 :(得分:1)
您只是致电Username
..您需要致电*
SELECT * FROM users WHERE Username LIKE ?
这是我使用的个人脚本:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
答案 1 :(得分:0)
您是否使用mysqli_stmt_init初始化语句对象?
答案 2 :(得分:0)
如果数据库服务器无法成功准备语句, PDO :: prepare()返回FALSE或发出PDOException(取决于错误 处理)
在创建连接对象后立即在connection.php
中添加此行:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
至少,您可以追踪可能的错误
答案 3 :(得分:0)
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>