1

我有几个问题都与同一个问题有关。我正在尝试将我的一些 MySQL 连接/命令更新到 PDO 以减轻 SQL 注入。我正在尝试转换此代码:

$ulog = $_POST['driver'];
$_SESSION['user_id'] = $ulog;
$tablename_cc = "cc_".$ulog;
$tablename_db = "db_".$ulog;
$tablename_misc = "misc_".$ulog;
$tablename_cash = "cash_".$ulog;

$sql_cc = "SELECT * FROM " .$tablename_cc;
$sql_db = "SELECT * FROM " .$tablename_db;
$sql_misc = "SELECT * FROM " .$tablename_misc;
$sql_cash = "SELECT * FROM " .$tablename_cash;

$result_cc = mysql_query($sql_cc);
$result_db = mysql_query($sql_db);
$result_misc = mysql_query($sql_misc);
$result_cash = mysql_query($sql_cash);

到以下代码:

$tables = array($tablename_cc, $tablename_db, $tablename_misc, $tablename_cash);

$A = count($tables);
$result = array();

try {
    $STH = $DBH->prepare('SELECT * FROM :table');
    $i = 0;
    while($i < $A) {
        $STH->bindParam(':table', $tables[$i]);
        $STH->execute();
        $result[$i] = $STH->fetchAll();
        $i++;
    }
}
catch(PDOException $e) {  
    echo $e->getMessage();
}

但是,我不断收到语法错误。如果我按以下方式尝试,错误就会消失,但这种方式对我来说不是很有用,因为它不能避免 SQL 注入。

try {
    $i = 0;
    while($i < $A) {
        $STH = $DBH->query('SELECT * FROM ' .$tables[$i]);
        $result[$i] = $STH->fetchAll();
        $i++;
    }
}
catch(PDOException $e) {  
    echo $e->getMessage();
}

尽管最后一种方法有效,但据我了解,它对减轻 SQL 注入没有帮助。我遇到的第二个问题是有时这些表不存在,我在旧方法中解决这些问题的方法是做一个小检查:

$result_cc = mysql_query($sql_cc);
if(mysql_num_rows($result_cc) != 0){}

但是,这个中间步骤似乎在 PDO 中消失了,所以我仍然需要弄清楚如何检查这个。

4

0 回答 0