我正在制作一个测试程序,我需要在其中使用以下代码:
"href=\"testmng.php?manageqn=" . htmlspecialchars_decode($r['testname'], ENT_QUOTES) . "?subjectname=". htmlspecialchars_decode($r['subname'], ENT_QUOTES)
我的问题是当 manageqn
和 subjectname
有正确的值时什么是正确的格式:
else if ((isset($_REQUEST['manageqn'])) && (isset($_REQUEST['subjectname']))) {
$testname = $_REQUEST['manageqn'];
$subname = $_REQUEST['subjectname'];
$result = executeQuery("select testid from test where testname='" . htmlspecialchars($testname, ENT_QUOTES) . "';");
if ($r = mysql_fetch_array($result)) {
$_SESSION['testname'] = $testname;
$_SESSION['subjectname'] = $subname;
$_SESSION['testqn'] = $r['testid'];
header('Location: prepqn.php');
}
}
最佳答案
假设您正在使用 mysqli 连接到数据库,您需要使用 myqli_real_escape_string() 对字符串进行转义PHP 函数,否则您可能会向您的应用程序添加 sql 注入(inject):
executeQuery("select testid from test where testname='" . myqli_real_escape_string($testname) . "';");
不过,我建议通过使用 mysqli 提供的准备好的语句功能来切换到参数化查询方法。然后,您可以像这样使用 executeQuery()
:
executeQuery("select testid from test where testname=?", $testname)
无需转义字符串即可进行安全查询。
如果您正在使用已弃用的 mysql
驱动程序,那么您应该使用 mysql_real_escape_string()
。
关于php - 正确的查询格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681119/