简体   繁体   中英

Inserting data into MySQL database using PDO

I'm new to PHP and MySQL and I'm trying to insert data in to a database, which had worked fine until i attempted to use PDO's prepare method. It returns the catch error and i cannot figure out why - i'd also like to know whether it's best practice to use unnnamed placeholders or named placeholders?

The username and password variables are defined earlier in my code and catches data from the user using $_POST .

EDIT: getMessage() error displays SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null

if (!empty($user) && (!empty($password)) ) {
    try {
        $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
        $results->bindParam(1,$username);
        $results->bindParam(2,$password);
        $results->execute();
    } catch (Exception $e) {
        echo "Could not insert data in to the database";
    }
}

You have two different variable names. You're checking $user to make sure it's not empty() but then you tell bind $username to the first parameter. You'll just need to rename one of them to match the other.

Try this one.

if (!empty($user) && (!empty($password)) ) {
try {
    $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
    $results->bindParam(1,$user);
    $results->bindParam(2,$password);
    $results->execute();
} catch (Exception $e) {
    echo "Could not insert data in to the database";
}

}

Please try yourself first to find the error.

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