Problems with insert INSERT mysql

Asked

Viewed 276 times

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();
?>
  • There’s one thing I’ve identified, you’re declaring a value of up to 11 characters in your email column email varchar,11, notnull and in his example just below the string $email has more than 11 characters, probably this may be an error, another observation I make is how is your connection?

1 answer

1


You have not commented on the made configuration to work with PDO. Because first of all, it is necessary to enable the PDO driver and the driver for the database that will be used.

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

Right after you should start connection to the bank:

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

And then enter the data into the database:

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

Adding an observation or warning to your code. It’s a lack of error handling. If you’re using it. Congratulations. It’s for your own good. If not, it would be interesting to start using, for example:

Make sure your connection has been successful. Use the 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 handling connection errors, the line has been added $conn->setAttribute(). The default PDO error is PDO::ERRMODE_SILENT. Switch to PDO::ERRMODE_EXCEPTION to enable error display. Below I will list the options you have:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.