PHP 检查用户是否存在 PDO

标签 php mysql pdo

我正在尝试实现该功能,它将检查用户是否已存在于我的数据库中,因为它将插入所有注册数据,但它似乎不起作用=(有人可以帮我确定在哪里错误是。非常感谢所有提前的回答。

<?php

require '../ppuyakul/php/db_conn.php';


$message = '';

//Prepare date
$DOB = date("Y-m-d", strtotime( $_POST['year'].'-'. $_POST['month'].'-'. $_POST['day']));
$accessType = "0";

//Check enpty field
if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['fullname']) && !empty($_POST['username']) && !empty($_POST['password_confirmation']) && !empty($_POST['gender']) && !empty($_POST['country']) && !empty($_POST['state']) && !empty($_POST['city']) && !empty($_POST['day']) && !empty($_POST['month']) && !empty($_POST['year'])):

  // Enter the new user in the database
  $sql = "INSERT INTO assignment2 (fullname, username, email, password, gender, country, state, city, DOB, type) VALUES (:fullname, :username, :email, :password, :gender, :country, :state, :city, :DOB, :type)";
  $stmt = $conn->prepare($sql);

  $stmt->bindParam(':fullname', $_POST['fullname']);
  $stmt->bindParam(':username', $_POST['username']);
  $stmt->bindParam(':email', $_POST['email']);
  $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
  $stmt->bindParam(':gender', $_POST['gender']);
  $stmt->bindParam(':country', $_POST['country']);
  $stmt->bindParam(':state', $_POST['state']);
  $stmt->bindParam(':city', $_POST['city']);
  $stmt->bindParam(':DOB', $DOB);
  $stmt->bindParam(':type', $accessType);

  $chk = $conn->prepare("SELECT username FROM assignment2 WHERE username =  :name");
  $chk->bindParam(':name', $username);
  $chk->execute();

  if($chk->rowCount() > 0):
    $message = 'Error ! ! User already exists';
    else:
      if( $stmt->execute() ):
        $message = 'Successfully created new user';
          else:
            $message = 'Sorry there must have been an issue creating your account';
          endif; 
      endif;
    endif;
?>

最佳答案

根据@Paul T。我终于找到了解决方案,这里是最终代码,再次感谢@Paul T 的帮助。

  $username = $_POST['username'];
  $chk = $conn->prepare("SELECT username FROM assignment2 WHERE username =  :name");
  $chk->bindParam(':name', $username);
  $chk->execute();


  if($chk->rowCount() > 0):
    $message = 'Error ! ! User already exists';
    else:
      if( $stmt->execute() ):
        $message = 'Successfully created new user';
          else:
            $message = 'Sorry there must have been an issue creating your account';
          endif; 
      endif;
    endif;

关于PHP 检查用户是否存在 PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212414/

相关文章:

php yii 框架对象问题

MySQL子查询与日期之间

mysql - 如何优化以下查询?

php - PDO 为带有命名占位符的 INSERT 和 ON DUPLICATE KEY UPDATE 准备语句

php - 未捕获的 PDOException 泄露用户名和密码

php - 根据指定的二级值比较二维数据集

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 如何在 PHP 中将所有图像转换为 JPG 格式?

php - 当从表中更新列行时,然后在该列的所有行中提取

PHP PDO 执行失败时事务会回滚吗?