Mysql function

如果是是用mysql function(ex:mysql_connect)
使用mysql_real_escape_string函式對字串過濾即可

mysql_real_escape_string($str);

PDO

若使用的是PDO

$dsn = "mysql:host=localhost;dbname=test";
$db = new PDO($dsn,"root","123");
$sql = "INSERT INTO news values('',?,?,'johnson')";//將需要過濾的欄位以?代替
$sth = $db -> prepare($sql);
$sth -> execute(array($_POST['new_title'],$_POST['editor'])) );//以字串陣列傳入

//select用法
$sth = $db -> prepare("SELECT * FROM news WHERE NID = ? LIMIT 1");
$sth -> execute(array($_GET['NID']));
$rows = $sth -> fetch();

PDO bindParam

$sth = $db -> prepare("SELECT * FROM news WHERE NID = :nid AND name = :name LIMIT :limit");
$sth->bindParam(':nid', $_GET['nid'], PDO::PARAM_INT);
$sth->bindParam(':name', $_GET['name'], PDO::PARAM_STR);
$sth->bindParam(':limit', intval($_GET['limit']), PDO::PARAM_INT);
$sth -> execute();

PDO::quote

$sql = "SELECT * FROM news WHERE NID=".$db -> quote($_POST[test])." LIMIT 1";
$db -> query($sql);
Categories: PHP