MsNichols
MsNichols

Reputation: 1133

PDO Insert Into DB

I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.

Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.

   $hostdb = 'myremoteip';
   $namedb = 'cpdemo';
   $userdb = 'root';
   $passdb = 'mypassword';

   $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);

   if(isset($_POST['fname'])) {

         $fname = $_POST['fname'];
         $lname = $_POST['lname'];
         $title = $_POST['title'];
         $photo = $_POST['photo'];

   $stmt = "INSERT INTO row_users (fname,lname,title,photo) 
         VALUES (:first,:last,:title,:photo)";

   $q = $conn->prepare($stmt);
   $results = $q->execute(array(
        ":first"=>$fname,
        ":last"=>$lname,
        ":title"=>$title,
        ":photo"=>$photo
    ));
    echo 'User Added<br/>';
    }

      header ('Location:../insertUser.html');
    exit();

Upvotes: 1

Views: 137

Answers (3)

Funk Forty Niner
Funk Forty Niner

Reputation: 74220

As requested by OP, comment leading to an answer (to close the question and marked as solved).

I tested your code "as is", and it worked fine.

The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))

Check to see if your HTML form's elements are indeed named?

I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157989

What you have to understand that there is no such thing like "PDO Insert Into DB"

There is INSERT query, irrelevant to PDO but regular to database you are using.
And there is PDO prepared statement, irrelevant to query type. You have to follow exactly the same pattern, no matter if it insert or delete.

So - all you need is just a tutorial on PDO prepared statements. That's all. Preferably one that teach you to enable error reporting in the first place.

Upvotes: 2

opensource-developer
opensource-developer

Reputation: 3068

You can try binding parameter before passing it to execute, like for example in the below code

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Upvotes: 0

Related Questions