Today, I read PHP to prevent SQL injection and use preprocessing prepare, but when I insert data, I can't insert it, but select can. After a long time, I finally know that the problem is here.
<?php header('content-type:text/html;charset=utf8');
//Receive form data
//$username = $_POST['username'];
$conn = new mysqli('localhost','root','akagami-666','water');
if($conn -> connect_errno){ echo "Connection failed".$conn -> connect_error; }
$sql = "insert into w_safe(name) values(?)";
// $sql = "select * from w_safe where name=?";
$stmt = $conn -> prepare($sql); $stmt -> bind_param("s",$username);
$username = $_POST['username'];
$stmt -> execute();
echo $stmt -> affected_rows;
$stmt -> close();
$conn -> close();
The reason for the problem is that I first received the post value, defined the $username variable, and then executed bind_param(), which made it impossible to insert data.
You must write bind_param() first, and the variables in the definition will work.
Hope it helps those who have the same problem! ! !