Name : Password : num_rows > 1){ -6ren">
gpt4 book ai didi

php - mysqli 查询在 php 中将列名作为一行返回

转载 作者:行者123 更新时间:2023-11-28 23:57:26 24 4
gpt4 key购买 nike

这是我的 login.php 文件

<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>

<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here

//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here


if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){

//echo "Name ".$_POST["name"];

if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here


/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>

一个问题是我的查询
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) 将列名称作为一行返回。不知道好不好?
另一件事是我输入了错误的名称或密码还是正确的,在这两种情况下我都没有得到任何输出。我在这里做错了什么?

如果可以的话,请告诉我如何用一个完整的例子用正确的格式在 php 中编写 mysqli 查询。我在谷歌上搜索过,但有不同的方法,所以当列名和变量出现在查询中时,我特别困惑。

最佳答案

您的 test_input 函数很弱/不安全,此外,mysql_query 已被删除,使用 mysqli 和准备好的语句,如下所述:http://php.net/manual/en/mysqli.prepare.php

此外,我还包含了一段用于我的登录系统的代码(使用盐等更复杂一些,您应该能够将其编译成适合您的脚本。

//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();

关于php - mysqli 查询在 php 中将列名作为一行返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247771/

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