Jump to content

Insert data into database by PDO

Recommended Posts

Hi everyone, I'm trying to use PDO to insert data in database, seem none of them success, it just breakdown after I click button to submit.

what did I do wrong?



/* check to see connection is working */
if(isset($_POST['submit'])) {

    $server = "localhost";
    $username = "Sigma";
    $password = "";
    $dbname = "Register";

try {
    $connect = new PDO ("mysql:host=$server;dbname=$dbname", $username, $password);
} catch (PDOException $error){
    echo $error->getMessage();

/* Insert data into database */
    $firsts = $_POST['first'];
    $lasts = $_POST['last'];
    $town = $_POST['town'];
    $states = $_POST['state'];
    $zip = $_POST['zip'];

    $insert = "INSERT INTO `Members`(`firstName`, `lastName`, `town`, `states`, `zip`) VALUES (:firsts,:lasts,:town,:states,:zip)";
    $result = $connect->prepare($insert);
    $result_run = $result->execute(array(":first"=>$firsts, ":last"=>$lasts, ":town"=>$town, ":state"=>$states, ":zip"=>$zip));

if($result_run) {
    echo '<script>alert("successfully added")"</script>';
} else {
    echo '<script>alert("failed added")"</script>';


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Gary's PDO website</title>
    <link rel="stylesheet"  type="text/css" href="CSS/insert.css">
    <h2>Welcome to Gary Taylor's Demonstration</h2>
    <h3>Insert Data in Database by PDO</h3>
<form action="index.php" method="post">
        <tr><th colspan="2">Register here</th></tr>
        <tr><td>First Name:</td><td><label><input type="text" name="first" placeholder="Ex: Gary">
        <tr><td>Last Name:</td><td><label><input type="text" name="last" placeholder="Ex: Taylor">
        <tr><td>Town:</td><td><label><input type="text" name="town" placeholder="Ex: Richmond">
        <tr><td>State:</td><td><label><input type="text" name="state" placeholder="Ex: VA">
        <tr><td>Zip Code:</td><td><label><input type="text" name="zip" placeholder="Ex: 23238">
        <tr><td colspan="2"><label><input type="submit" name="submit" value="Insert into database"></label></td></tr>


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...