About MySQL INSERT INTO

Asked 2 years ago, Updated 2 years ago, 46 views

I'm studying php, MySQL based on a textbook.

If the form information is entered correctly, it will display "1 was inserted" and
The information should be stored in the database, but it will not be processed correctly.

「 It comes with -1 was inserted and -.
データベース It will not be saved in the database.

Could you tell me what caused it?

<html>
<head>
</head>

<body>

<form method="post" action="insert.php">
Name: <input type="text" name="name"/><br/>
Email: <input type="text" name="email"/><br/>
Password: <input type="password" name="password"/>br/>
<input type="submit" value="register"/><br/>
</form>

</body>
</html>
<?php

$name = $_POST ["name" ];
$email=$_POST["email"];
$password=$_POST["password"];

if($name&&$email&$password){
    mysql_connect("localhost", "root", "") or die("we could not connect!");
    mysql_select_db("testsite");
    mysql_query("INSERT INTO users(name, email, password)VALUES($name,$email,$password)");
    $registered=mysql_affected_rows();
    echo "$registered was inserted";
} else{
    echo "you have to complete the form";
}

mysql_close();

?>

php mysql

2022-09-29 22:56

1 Answers

mysql_affected_rows returns -1 when the last query fails.

https://stackoverflow.com/questions/6722809/mysql-affected-rows-returns-1

For a reason, $name or $email or $password are probably strings; they are treated as literal when used in "...".For example, if $name contains test, $email contains [email protected], and $password contains my-password, the query is

INSERT INTO users (name, email, password) VALUES (test, [email protected], my-password)

is the case.What I'm actually looking forward to is

INSERT INTO users(name, email, password) VALUES('test', '[email protected]', 'my-password')

That's right. So

mysql_query("INSERT INTO users (name, email, password) VALUES('$name', '$email', '$password')";

Some people write "Please..." but this is the worst thing to do.

mysql_query(sprintf("INSERT INTO users(name, email, password) VALUES('%s', '%s', '%s')",
    mysql_real_escape_string($name),
    mysql_real_escape_string($email),
    mysql_real_escape_string($password)));

You should use mysql_real_escape_string to escape, or use PDO to prepared statements.

http://php.net/manual/ja/pdo.prepared-statements.php

I think you can learn more about why you shouldn't do it by looking at Tokumaru's website.

http://blog.tokumaru.org/


2022-09-29 22:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.