I have a very simple code to insert data into database, also checks if already has same data in table
[HTML]
<html>
<head>
<title>nickname</title>
</head>
<body>
<p>input nickname</p>
<form action="foo.php" method="post">
<input type="text" name="nickname" />
<input type="submit">
</form>
</body>
</html>
[PHP]
//foo.php
if(isset($_POST['nickname']) && !empty($_POST['nickname'])) {
$nickname = $_POST['nickname'];
//Object Oriented way
$servername = "localhost";
$username = "root";
$password = "foo_bar";
$dbname = "nickname";
//check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("cannot connect:".$conn->connect_error);
}
$sql = "SELECT * FROM nickname WHERE nickname='$nickname'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo "nickname exists!";
} else {
$sql = "INSERT INTO nickname(nickname) VALUES(".$nickname.")";
$conn->query($sql);
echo "welcome $nickname!";
}
$conn->close();
} else {
echo "please input your nickname";
}
I am still learning how to use MySQL, what am I doing wrong? especially this line
$sql = "INSERT INTO nickname(nickname) VALUES(".$nickname.")";
$conn->query($sql);
the data in the variable is not inserted to table, nothing happens.
but if I replace $nickname
to plain text the data is inserted.
edit
why is this a duplicate? the question is not even about "how to prevent sql injection"