2019-07-15 11:17
浏览 62


I'm learning to create conditional event where sql checkout data where is exists before inserting data so they don't conflicted.

i've tried using mysql row check in php then check if query empty before i tried to validate the query executed properly.

also trying to close db connection when conditional satisfied but it worthless anyway.

$user = addslashes(strtolower($usr));
$mail = addslashes(strtolower($mail));
$pass = md5(addslashes($pwd));

$check = $db->query("SELECT EXISTS(SELECT * 
                                   FROM `users`
                                   WHERE LOWER(`username`) = LOWER('$user')
                                      OR LOWER(`email`) = LOWER('$mail'))");

if (!$check) {
    return false;
} else {
    $sql = "INSERT IGNORE INTO `users` (`username`, `password`, `email`)
                   VALUES ('$user', '$pass', '$mail')";
    $query = $db->query($sql);
    return true;

I'm expecting it execute my queries while data was empty and return false while data has been existed.

图片转代码服务由CSDN问答提供 功能建议

我正在学习创建条件事件,其中在插入数据之前存在sql checkout数据,因此它们不会冲突 。


还尝试 在条件满足时关闭数据库连接,但无论如何都没有价值。

  $ user = addslashes(strtolower($ usr)); 
  $ mail = addslashes(strtolower($ mail)); 
 $ pass = md5(addslashes($ pwd)); 
 $ check = $ db-> query(“SELECT EXISTS(SELECT * 
 FROM FROM)  users` 
 WHERE LOWER(`username`)= LOWER('$ user')
 OR LOWER(`email`)= LOWER('$ mail'))“); 
if(!$ check){  
 $ db-> close(); 
} else {
 $ sql =“INSERT IGNORE INTO`user`(`username`,`password`,`email`)
 VALUES(  '$ user','$ pass','$ mail')“; 
 $ query = $ db-> query($ sql); 
 $ db-> close(); 
返回true; \  n} 


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dphs48626 2019-07-15 11:35

    Your main issue is that $check will always be a truthy value, so long as the query never fails. If the query returns 0 rows, it is still a true object.

    You should instead check if there were any values returned. You can also simplify the query quite a bit, given that MySQL is case-insensitive, and you don't need to check if the result exists. Using a prepared statement, the code would look like this

    $stmt = $db->prepare("SELECT username FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $usr, $mail);
    $check = $stmt->fetch();
    // True if the user exists 
    if ($check) { 
        return false;
    } else {
        $stmt = $db->prepare(" INSERT INTO users (username, password, email) VALUES (?, ?, LOWER(?))");
        $stmt->bind_param("sss", $usr, $pass, $mail);

    That said, you should not use md5() for passwords - use password_hash() with password_verify() instead.

    解决 无用
    打赏 举报

相关推荐 更多相似问题