-2

Can anyone tell me what am I doing wrong here? I am new to PDO and need to learn how to insert using bindValue but nothing is been added to my database when I hit submit. Not even an error is shown.

Can anyone give an example. Below is my code:

<!DOCTYPE html>
<html lang="eng">
<head><title>PDO INSERT TEST</title>
<meta http-equiv="CONTENT-TYPE" CONTENT="text/html;charset=utf-8"/>
</head>
<body>
<form action="PDO_test1.php" method="POST">
<p>Name: <input type="text" name="userName" id="Name"/></p>
<p>Last: <input type="text" name="userLast" id="Last"/></p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

<?php 
    # basic pdo connection (with added option for error handling)
    if (isset($_POST['submit'])) {

        require_once 'includes/PDO_connect.php';
        try {
            $dsn = "mysql:host=$servername;dbname=$dbname";
            $dbc = new PDO($dsn, $username, $password);
            //You can echo out connected to db message
            $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $query = $dbc->prepare("INSERT INTO `PdoTest1` (userName,userLast,reqistration_date) VALUES (?, ?, ?)");
            # If we leave out the third parameters, it is set to
            # PDO::PARAM_STRING by default
            $query->bindValue(':userName', '%' . $_POST['userName'] . '%');
            $query->bindValue(':userLast', '%' . $_POST['userLast'] . '%');
            $dbc = null;
        }

        catch (PDOException $e) {
            echo $e->getMessage();
        }
        //echo "<p>Data submitted successfully</p>";
    }
?>
Dan Lowe
  • 51,713
  • 20
  • 123
  • 112

1 Answers1

0

You should read the examples given in the manual:

http://php.net/manual/es/pdostatement.bindvalue.php

They are going to help you a lot. Reading them you could change your code like this:

$query = $dbc->prepare( "INSERT INTO `PdoTest1` (userName,userLast,reqistration_date) 
VALUES (?, ?, NOW())");
# If we leave out the third parameters, it is set to
# PDO::PARAM_STRING by default
$query->bindValue(1, $_POST['userName']);
$query->bindValue(2, $_POST['userLast']);
$query->execute();

Or if you preffer the other sintax:

$query = $dbc->prepare( "INSERT INTO `PdoTest1` (userName,userLast,reqistration_date) 
VALUES (:username, :userLast, NOW())");
# If we leave out the third parameters, it is set to
# PDO::PARAM_STRING by default
$query->bindValue(':username', $_POST['userName']);
$query->bindValue(':userLast', $_POST['userLast']);
$query->execute();
Gonzalo
  • 1,781
  • 15
  • 29