我有这段代码:
<link rel="stylesheet"href="includes/css/bootstrap.min.css"><?php
require_once "class.php";
$conn = new db_class();
if(ISSET($_POST['signup'])){
$username = $_POST['username'];
$password = sha1($_POST['password']);
$confpassword = sha1($_POST['confpassword']);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$conn->save($username, $password,$confpassword, $firstname, $lastname);
} ?>
这是功能:
public function save($username, $password,$confpassword, $firstname, $lastname){
$stmt = $this->conn->prepare("SELECT * FROM `user` WHERE `username` = '$username'") or die($this->conn->error);
if($stmt->execute()){
$result = $stmt->get_result();
if($password!=$confpassword){
echo "<div class=\"alert alert-danger\"><strong>password does not match</strong></div>";
}else
if( $result->num_rows == 0){
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
除了这个警告外,一切都很顺利:
警告:mysqli_stmt :: bind_param():类型中的元素数 定义字符串与C:\ Program中的绑定变量数不匹配 档 (x86)\ EasyPHP-DevServer-14.1VC11 \ data \ localweb \ segments \ class.php on 第214行
任何想法?我试着在这里添加更多“s”:
$stmt1->bind_param("s", $username, $password, $confpassword, $firstname, $lastname);
仍然有同样的警告。有什么想法吗?
答案 0 :(得分:2)
使用预准备语句时,必须使用占位符。没有他们,你不仅会得到不必要的致命错误,而且你正在击败使用准备好的陈述。
您绑定了5个变量,因此需要5个占位符来绑定它们。
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?, ?,?, ?, ?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
答案 1 :(得分:1)
这是错误的
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES('$username', '$password','$confpassword', '$firstname', '$lastname')") or die($this->conn->error);
您需要使用您将绑定的占位符而不是上面的变量
这就是你需要的:
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)") or die($this->conn->error);
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
更新:
这个or die($this->conn->error);
在你把它放在查询没有被执行的地方是没用的,在你准备的那一行,你需要在execute()
之后检查成功/失败
因此应该像:
<?php
$stmt1 = $this->conn->prepare("INSERT INTO `user` (username, password, confirmPass, firstname, lastname) VALUES(?,?,?,?,?)");
$stmt1->bind_param("sssss", $username, $password, $confpassword, $firstname, $lastname);
$stmt1->execute();
if(!$stmt1){
die($this->conn->error);
}
?>