好吧,我正在为我的网站创建一个注册系统,但是我在执行查询时遇到了问题。我试图解决问题,但我没有成功。有点困惑:(
这是我的代码:
public function registerUser($username, $password, $email) {
global $core;
if(empty($username) || empty($password) || empty($email)) {
throw new Exception ('A required field was left blank');
} else {
//SQL Query Data
$data['username'] = $username;
$data['password'] = $core->encrypt($password);
$data['email'] = $email;
$data['userKey'] = rand(999999, 100000);
$data['ip'] = $_SERVER['REMOTE_ADDR'];
$data['date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->query($sql);
$STH->execute($data);
}
}
这是我得到的错误:
Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\community\inc\user.inc.php on line 33
我猜这是查询的错误,但我不确定是什么!
答案 0 :(得分:1)
我认为你PDO::prepare()混淆了PDO::query():
应该是:
$result = $this->DBH->query($sql);
或者:
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
来自文档:
PDO::query()在单个函数调用中执行SQL语句, 返回语句返回的结果集(如果有)作为 PDOStatement对象。
如果要重复发出相同的语句,或者需要绑定参数,通常会使用PDO::prepare()。据我所知,在使用PDO::query()之前无法将参数绑定到您的查询。
请注意,使用PDO::prepare(),您可以在调用PDOStatement::bindParam()之前使用PDOStatement->execute()绑定参数,也可以将参数作为数组传递给PDOStatement->execute()。
您还需要在数组键前添加冒号前缀。所以最终结果将是:
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
答案 1 :(得分:0)
你应该在插入查询中使用`quote而不是'。
“插入u_userdata
user-key
,username
,password
,email
,register-ip
,register-date
)价值观( :userKey,:username,:password,:email,:ip,:date)
答案 2 :(得分:0)
query()函数执行sql语句。你应该使用prepare()函数。 我假设你正在使用pdo,因为pdo标签
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
$data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$stmt = $this->DBH->prepare($sql);
$stmt->execute($data);