简体   繁体   中英

Inserting data to database using PDO

I try to make registration form using PDO.I got next form:

<form name="registration" action="registration.php" method="POST">
      <label for 'username'>Username: </label>
            <input type="text" name="userName"/>
      <label for 'password'>Password: </label>
            <input type="password" name="pass"/>
      <label for 'first_name'>First name: </label>
            <input type="text" name="fullName"/>

      <label for 'email'>Email: </label>
            <input type="text" name="email"/>
      <br/>
      <button type="submit">Submit</button>
 </form>

And I got registration.php file to connect database and insert values:

    <?php


$user = 'root';
$pass = '8169x5it';
$db = new PDO( 'mysql:host=localhost;dbname=reg_form', $user, $pass );

$form = $_POST;
$usernName = $form[ 'userName' ];
$pass = $form[ 'pass' ];
$fullName = $form[ 'fullName' ];
$email = $form[ 'email' ];


$sql = "INSERT INTO WebsiteUsers ( userName, pass, fullName, email ) VALUES ( :userName, :pass, :fullName, :email )";

$query = $db->prepare( $sql );
$query->execute( array( ':userName'=>$userName, ':pass'=>$pass, ':fullName'=>$fullName, ':email'=>$email ) );
?>

So, the problem is when I put some in fileds and press Submit button my data NOT insert to database. Please help me, I'm new in PDO and mysql and I can't understand what's wrong. Thanks in advance!

  • Check for errors
  • Remove unnecessary variables
  • Check if post variables are set with isset()

try{
    $user = 'root';
    $pass = '8169x5it';
    $db = new PDO( 'mysql:host=localhost;dbname=reg_form', $user, $pass );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO WebsiteUsers ( userName, pass, fullName, email ) 
            VALUES ( :userName, :pass, :fullName, :email )";

    if($query = $db->prepare($sql)){
        $query->bindValue(':userName', $_POST['userName']); 
        $query->bindValue(':pass', $_POST['pass']); 
        $query->bindValue(':fullName', $_POST['fullName']); 
        $query->bindValue(':email', $_POST['email']); 
        if($query->execute()){
            echo 'execute() success ';
            echo 'affected rows = '.$stmt->rowCount();
        }else{
            echo 'execute() failed';
        }
    }else{
        echo 'prepare() failed';
    }
}catch(PDOException $e) {
    // Print PDOException message
    echo $e->getMessage();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM