天天看點

PHP防止資料庫數字SQL注入攻擊

<?php

header("Content-Type:text/html;charset=UTF-8");

// 資料庫配置

include_once 'config.php';

// 獲得傳遞參數

$id=urldecode($_GET['id']);

// 判斷是否有參數

$id = isset($_GET['id']) ? $_GET['id'] : '';

// 防止SQL注入

if (empty($id) || !is_numeric($id))

{

    die("警告:這個是非法數字!");

}

// 連接配接資料庫

$conn=mysql_connect($Db_Server,$Db_User,$Db_Pwd);

// 判斷連接配接是否成功

if (!$conn)

die("不能連接配接資料庫,錯誤是: " . mysql_error());

// 資料庫輸出編碼,應該與你的資料庫編碼保持一緻。建議用UTF-8國際标準編碼

mysql_query("set names 'utf8'"); 

// 打開資料庫

$db_selected = mysql_select_db($Db_Name, $conn);

// 判斷打開是否成功

if (!$db_selected)

die ("不能打開資料庫,錯誤是: " . mysql_error());

// SQL語句

$sql ="select * from demo where id=".$id;

// 查詢SQL語句

$result = mysql_query($sql,$conn); 

// 判斷是否有資料

if (!$result)

die("查詢失敗: " . mysql_error());

// 循環讀取資料

while($row = mysql_fetch_array($result))

// 讀資料

echo $row['content'];

// 使用完畢關閉資料庫連接配接

mysql_close();

?>