今天看了PHP防SQL注入,使用預處理prepare,可是我insert數據時,老是插不進去,可是select卻能夠,弄了好久終於知道原來問題在這裏,先上代碼php
<?php header('content-type:text/html;charset=utf8');html
//接收表單數據 mysql
//$username = $_POST['username'];sql
$conn = new mysqli('localhost','root','akagami-666','water'); post
if($conn -> connect_errno){ echo "鏈接失敗".$conn -> connect_error; } spa
$sql = "insert into w_safe(name) values(?)"; htm
// $sql = "select * from w_safe where name=?"; mysqli
$stmt = $conn -> prepare($sql); $stmt -> bind_param("s",$username); 變量
$username = $_POST['username']; 表單
$stmt -> execute();
echo $stmt -> affected_rows;
$stmt -> close();
$conn -> close();
出問題的緣由就是,我一開始是先接收post值,定義$username變量,後執行bind_param(),而這就致使沒法插入數據,
必需要先寫bind_param(),在定義裏面的變量才行。
但願能幫助遇到一樣問題的小夥伴!!!