我正在关注youtube教程,我收到此错误,因为我仍然是php的初学者,因此我不确定如何修复。你们能帮助我吗?我也在使用phpmyadmin。我会发布一些代码。
我的错误:
致命错误:未捕获PDOException:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(
socialnetwork
。login_tokens
,CONSTRAINT {{1}在D:\ xampp \ htdocs \ test \ classes \ DB.php中的FOREIGN KEY(login_tokens_ibfk_1
)参考id
(users
)):14堆栈跟踪:#0 D:\ xampp \ htdocs \ test \ classes \ DB.php(14):PDOStatement-> execute(Array)#1 D:\ xampp \ htdocs \ test \ login.php(19):DB :: query(' INSERT INTO log ...',Array)#14 {main}在第14行的D:\ xampp \ htdocs \ test \ classes \ DB.php中抛出
我的login.php
id
我的DB.php
<?php
include('classes/DB.php');
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))){
if(password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])){
echo 'Logged in!';
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong)); //generate a hex of random bytes for token
$user_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
DB::query('INSERT INTO login_tokens VALUES (\'\', :token, :user_id)', array(':token'=>sha1($token), 'user_id'=>$user_id)); // passing token into user_id, uses sha1 to hash token for encryption
//SNID variable meaning social network id, expires date, current time, seconds, mins, 1 day, 7 valid for 1 week, server / for everywhere, domain for where you are hosting, SSL - set to true if it is using ssl, http only
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
//second cookie that will expire every 3 days. Ask for server for another cookie. Without them knowing and they dont have to log in/out.
setcookie("SNID_", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
}else{
echo 'username or password is incorrect!';
}
}else {
echo 'User not registered!';
}
}
?>
我的index.php
class DB{
private static function connect(){
$pdo = new PDO('mysql:host=127.0.0.1;dbname=socialnetwork;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()){
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT'){
$data = $statement->fetchAll();
return $data;
}
}
}
在我的phpMyAdmin的login_tokens中:
姓名:id 类型:整数(11) 整理: 属性:UNSIGNED 空:没有 默认值:无 额外:AUTO_INCREMENT 小学
名称:令牌 类型:char(64) 整理:latin1_swedish_ci 属性: 空:没有 默认值:无 Keyname:令牌 独特:是的 打包:没有 列标记 基数:0 整理:A 空:没有
名称:user_id 类型:整数(11) 整理: 属性:UNSIGNED 空:没有 默认值:无