0

I'm new with PDO and I have little problem. Code is not inserting any data in my database, don't know why. Something wrong with binding or sth else?

<form action="" method= "POST">
    First name: <input type="text" name="data_name"><br>
    E-mail: <input type="email" name="data_mail"><br>
    City: <input type="text" name="data_city"><br>
    <input type="submit" value="Submit">
</form>

<?php

    $dsn = 'mysql:host=localhost;dbname=tabelaDB';
    $username = 'root';
    $password = 'pass';

    $db = new PDO($dsn, $username, $password);

    $name = $_POST['data_name'];
    $mail = $_POST['data_mail'];
    $city = $_POST['data_city'];

    $sql = $db->prepare( "INSERT INTO data ( data_name, data_mail, data_city ) VALUES ( :data_name, :data_mail, :data_city )");

    $sql->bindValue(':data_name', $name);
    $sql->bindValue(':data_mail', $mail);
    $sql->bindValue(':data_city', $city);

    $sql->execute();
?>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
bonzo7aab
  • 31
  • 9

2 Answers2

2

Surrond your PHP code with try - catch block as here: http://php.net/manual/en/pdo.error-handling.php then you get all information about your error.

Eidt: Here: PDO error message? is similar problem and another soultion.

Community
  • 1
  • 1
Blady214
  • 729
  • 6
  • 19
1

First thing you should put the PHP block in a IF statement to check if the form is submited or a user just opens the page:

<?php
if(isset($_POST['submit'])){
$dsn = 'mysql:host=localhost;dbname=tabelaDB';
$username = 'root';
$password = 'pass';

$db = new PDO($dsn, $username, $password);

$name = $_POST['data_name'];
$mail = $_POST['data_mail'];
$city = $_POST['data_city'];

$sql = $db->prepare( "INSERT INTO data ( data_name, data_mail, data_city ) VALUES ( :data_name, :data_mail, :data_city )");

$sql->bindValue(':data_name', $name);
$sql->bindValue(':data_mail', $mail);
$sql->bindValue(':data_city', $city);

$sql->execute();
}
?>

To check for errors add before prepare :

$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

Then add

print_r($db->errorInfo());
ka_lin
  • 9,329
  • 6
  • 35
  • 56