我们如何在PhP中编码mysql特殊字符?

时间:2012-03-29 06:02:46

标签: php mysql

我让这个php程序访问mysql数据

foreach ($arrayOfID as $ID)     {
    $IDWhere[]="TB.ID LIKE '" .$ID."'";
    //$IDWhereOther[]="Business LIKE '".$ID."'";
    //  $IDWhereFinalOther1[]=$ID;
    $IDWherePhone[]="BusinessID LIKE '".$ID."'";
    //$IDWhereURLandImage[]="`Business ID` LIKE '".$ID."'";
    $newOutput[$ID]=array();
    $copy[$ID]=array(); 
    keyID2[]=$ID;
    $IDtoBuilding[]="TB.ID LIKE '".$ID."'";
}
IDWhereFinal=implode(" OR ", $IDWhere);
//$IDWhereFinalOther=implode(" OR ", $IDWhereOther);
//$IDFinalBuilding=implode(" OR ", $IDtoBuilding);  
//$query="Select *, Country FROM `tablebusiness` As TB, `tablecity` As TC WHERE (".$IDWhereFinal.") AND TB.City=TC.City";
//$query="Select *, Country, Building.Title FROM `tablebusiness` As TB, `tablecity` As TC, `tablebusiness` As Building WHERE (".$IDWhereFinal.") AND TB.City=TC.City And (Building.ID=TB.Building OR TB.Building=0)";
 //$query="Select *, Country, COALESCE(NULL,(select Title from `tablebusiness` As TBuild where  TBuild.ID=TB.Building)) as BuildingTitle FROM `tablebusiness` As TB,  `tablecity` As TC, `tablebusiness` As Building WHERE (".$IDWhereFinal.") AND TB.City=TC.City";
$query="Select *, Country, (select Title from `tablebusiness` As TBuild where TBuild.ID=TB.Building) as BuildingTitle FROM `tablebusiness` As TB, `tablecity` As TC WHERE TB.City=TC.City and (".$IDWhereFinal.")";
$data = mysql_query($query);

问题是,有时$ID包含'

我认为应将其转义为''

'可能不是唯一的问题

也许还有其他字符也应编码。

那是否有功能?

2 个答案:

答案 0 :(得分:1)

绝对。您必须使用mysql_real_escape_string。这对安全性也有好处,基本上你应该每次在DB中插入数据时(除非它不是字符串,然后转换为int / float / etc就可以了)

答案 1 :(得分:1)

这样做的现代方法是使用PHP的PDO扩展和预处理语句,它们可以为您处理正确的转义。所以你的查询会变成这样的

Select *, Country, (
    select Title from `tablebusiness` As TBuild 
    where TBuild.ID=TB.Building) as BuildingTitle 
FROM `tablebusiness` As TB, `tablecity` As TC 
WHERE TB.City=TC.City and (TB.ID LIKE ? OR BusinessID LIKE ?)