M
M
mihailos2020-04-15 06:08:43
PHP
mihailos, 2020-04-15 06:08:43

Why is the data not being added to the database?

<?php
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['pass'];
try{
    $conn = new PDO('mysql:host=localhost; dbname=testbd', 'root', '');
    $sql = "INSERT INTO users (login, email, password)
            VALUES($login, $email, $password)";
    $conn->exec($sql);
    }
catch(PDOExeptions $e){
    echo $sql . $e->getMessage();
    header("Location: index.php");
}
?>


Here is the form
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Вход</title>
</head>
<body>
    <form action="/check.php" method="post">
        <p><input type="text" placeholder="Введите логин" name="login"></p>
        <p><input type="email" placeholder="Введите email" name="email"></p>
        <p><input type="password" name="pass" placeholder="Введите пароль"></p>
        <p><input type="submit"></p>
    </form>
</body>
</html>

No errors occur, but the data is not added to the database
Why??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-04-15
@mihailos

Errors don't occur because you didn't tell the PDO to report them to you.
And not added because you're doing everything wrong. Variables are never added directly to a query. Plus, there are a lot of unnecessary things in the code.
Here you can see a normal example.
First, the query must be prepared by putting question marks instead of variables, and then executed by passing the variables separately

<?php
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['pass'];
$conn = new PDO('mysql:host=localhost; dbname=testbd', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$sql = "INSERT INTO users (login, email, password) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$login, $email, $password]);

And everything will always work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question