我有一个登录屏幕,用户输入他们的用户名和密码。我设法使用PDO连接到数据库,但我必须将其更改为mysqli。请有人帮我转换成mysqli。提前致谢。
PDO:
<?php
try {
$database = new PDO('mysql:host=localhost;dbname=myfiles', 'root', '',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$query = "SELECT * FROM users WHERE Username = ? AND Password = ?";
$userParam = array($_POST["Uname"], $_POST["Pass"]);
$st = $database->prepare($query);
$st->execute($userParam);
$getResults = $st->fetch(PDO::FETCH_ASSOC);
session_start();
$_SESSION['details']['username'] = $getResults['Username'];
$_SESSION['details']['password'] = $getResults['Password'];
unset($database);
header("Location: index.php");
}
catch(PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
?>
Mysqli(这是我试过的)
<?php
try {
$database = mysqli_connect("localhost", "root", "", "myfiles");
$query = mysqli_query("SELECT * FROM users WHERE Username = ? AND Password = ?");
$userParam = array($_POST["Uname"], $_POST["Pass"]);
$st = $database->prepare($query);
$st->execute($userParam);
$getResults = mysqli_fetch_assoc($query);
session_start();
$_SESSION['details']['username'] = $results['Username'];
$_SESSION['details']['password'] = $results['Password'];
unset($database);
header("Location: index.php");
} catch (Exception $e ) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
?>
运行Mysqli代码时出错:
Warning: mysqli_query() expects at least 2 parameters, 1 given in G:\xampp\htdocs\old\drop\login.php on line 39
Fatal error: Call to a member function execute() on a non-object in G:\xampp\htdocs\old\drop\login.php on line 43
更新
的mysqli
<?php
try {
$database = mysqli_connect("localhost", "root", "", "myfiles");
$query = "SELECT * FROM users WHERE Username = ? AND Password = ?";
$userParam = array($_POST["Uname"], $_POST["Pass"]);
$st = $database->prepare($query);
$st->execute($userParam);
$getResults = mysqli_fetch_assoc($st);
session_start();
$_SESSION['details']['username'] = $getResults['Username'];
$_SESSION['details']['password'] = $getResults['Password'];
unset($database);
header("Location: index.php");
} catch (Exception $e ) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
?>
"Waiting for localhost"
答案 0 :(得分:2)
你的问题在这里:
$query = mysqli_query("SELECT * FROM users WHERE Username = ? AND Password = ?");
$userParam = array($_POST["Uname"], $_POST["Pass"]);
$st = $database->prepare($query);
$st->execute($userParam);
prepare
期望一个字符串,mysqli_query
是一个执行查询的过程函数。删除它。此外,使用mysqli,您需要先绑定参数,而不是将它们传递给execute()
。
$query = "SELECT * FROM users WHERE Username = ? AND Password = ?";
$st = $database->prepare($query);
$st->bindParam("ss",$_POST["Uname"], $_POST["Pass"]);
$st->execute();
以下是手册的相关部分:
http://php.net/manual/en/mysqli.prepare.php
答案 1 :(得分:0)