INSERT insertion problems mysql

0

I am trying to insert data into my mysql database but the values do not appear in the table

TABELA "users":
id 'int','11', 'notnull','primarykey','auto increment'
email 'varchar','11', 'notnull'
senha 'varchar','11', 'notnull'
<?php
$email = '[email protected]';
$senha = '12345';

$query = 'INSERT INTO users (email,senha) VALUES ('.$email.','.$senha.')';
$stmt = $conn->prepare($query);
$stmt->execute();
?>
    
asked by anonymous 14.07.2017 / 07:47

1 answer

1

You did not comment on how you did the setup to work with PDO. First of all, it is necessary to enable the PDO driver and the driver for the bank that will be used.

In this link there is a tutorial on how to do this.

Soon after you should start connecting to the bank:

$con = new PDO("mysql:host=localhost;dbname=nome_banco", "root", "senha"); 

And then enter the data in the database:

$query = 'INSERT INTO users (email,senha) VALUES ('.$email.','.$senha.')';
$stmt = $conn->prepare($query);
$stmt->execute();

Adding a note or alert to your code. It is the lack of error handling. If using. Congratulations. It's for your own good. If it is not, it would be interesting to start using, for example:

Make sure your connection is successful. Use block try{}catch(){} :

$try {
    con = new PDO("mysql:host=localhost;dbname=nome_banco", "root", "senha");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = 'INSERT INTO users (email,senha) VALUES ('.$email.','.$senha.')';
    $stmt = $conn->prepare($query);
    $stmt->execute();
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

In addition, for connection error handling, the $conn->setAttribute() line has been added. The default PDO error is PDO::ERRMODE_SILENT . Switch to PDO::ERRMODE_EXCEPTION to enable error display. Below I will list the options you will have:

  • PDO :: ERRMODE_SILENT
  • PDO :: ERRMODE_WARNING
  • PDO :: ERRMODE_EXCEPTION

After validating this information, try running your INSERT . Error case, update your question with the error so we can help you better.

    
14.07.2017 / 12:23