dear Stackoverflow users, I start learning PHP and MySQLi. And now I have some issues. On every page reload in DB added 1 full empty row, every cell is null. Can someone give me advice about issue? Code below:
PHP before html tag:
<?php
$mysqli = new mysqli("", "", "", "");
$mysqli->set_charset('utf8');
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$link = $mysqli->real_escape_string($_POST['link']);
$query = "INSERT INTO demos (name, email, link) VALUES ('$name', '$email', '$link')";
$mysqli->query($query);
$mysqli->close();
?>
HTML inside body tag:
<form action="" method="post">
<input type="text" name="name" maxlength="20" required />
<input type="text" name="email" required />
<input type="text" name="link" required />
<input type="submit" value="Send" />
</form>
You should first check if your form is submitted by using isset or !empty.
By using isset, you can check wether or not a variable is set:
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['link'])) {
// your code
}
?>
By using !empty, you can check if a variable is set and not empty. Note however that if you are using empty you can not submit a '0' or leave a field blank.
<?php
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['link'])) {
// your code
}
?>
Try using prepared statement for easier use and protection for SQL injection:
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $name, $email,$link);
$stmt->execute();
Read more about prepared statements: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Use var_dump to debug your code to make sure the values are not null
Add this before and after escaping the strings:
var_dump(array($name, $email, $link));
Also, switch to using prepared statements
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES (?,?,?)");
$stmt->bind_param('sss', $name, $email, $link); // bind vars to the parameter
$stmt->execute(); // Execute statement