Advertisement
Guest User

Untitled

a guest
May 25th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.52 KB | None | 0 0
  1. <?php
  2.    
  3.     /**
  4.     *   Connect to DB
  5.     */
  6.  
  7.     $host = "localhost";
  8.     $user = "root";
  9.     $pass = "";
  10.     $dbname = "content";
  11.  
  12.     try {
  13.  
  14.         $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
  15.  
  16.         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  17.  
  18.     }
  19.  
  20.     catch(PDOException $e) {
  21.  
  22.         echo "Connection failed: " . $e->getMessage();
  23.  
  24.     }
  25.  
  26.  
  27.     if(isset($_POST['user'])) {
  28.  
  29.         $username = trim($_POST['user']);
  30.  
  31.         /**
  32.         *   Set error to empty in the beginning...
  33.         */
  34.  
  35.         $error = '';
  36.  
  37.         /**
  38.         *   Example of form validation...
  39.         */
  40.  
  41.         if(empty($username)) {
  42.  
  43.             $error = "You must enter a username.";
  44.  
  45.         }
  46.  
  47.         /**
  48.         *   If the error is still empty, we can go ahead
  49.         *   and run our query...
  50.         */
  51.  
  52.         if($error == '') {
  53.  
  54.             $sql = "SELECT * FROM users WHERE username = :username";
  55.  
  56.             $stmt = $conn->prepare($sql);
  57.  
  58.             $stmt->bindParam(":username", $username, PDO::PARAM_STR);
  59.  
  60.             $stmt->execute();
  61.  
  62.             //var_dump($stmt->execute());
  63.  
  64.             if($stmt->rowCount() > 0) {
  65.  
  66.                 $error = "That user name is taken...";
  67.  
  68.             } else {
  69.  
  70.                 $error = "Username is not taken...";
  71.  
  72.             }
  73.  
  74.         }
  75.  
  76.         $data = array(
  77.  
  78.             'error'  => $error
  79.  
  80.         );
  81.  
  82.         echo json_encode($data);
  83.  
  84.     } else {
  85.  
  86.         die("Cannot access this file directly...");
  87.        
  88.     }
  89.  
  90. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement