Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting mysql_query multi-table select command to PDO
    primarykey
    data
    text
    <p>I have a couple of questions all pertaining to the same problem. I'm trying to update some of my MySQL connections/commands to PDO in order to mitigate SQL injections. I'm trying to convert this code:</p> <pre><code>$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); </code></pre> <p>To the following code:</p> <pre><code>$tables = array($tablename_cc, $tablename_db, $tablename_misc, $tablename_cash); $A = count($tables); $result = array(); try { $STH = $DBH-&gt;prepare('SELECT * FROM :table'); $i = 0; while($i &lt; $A) { $STH-&gt;bindParam(':table', $tables[$i]); $STH-&gt;execute(); $result[$i] = $STH-&gt;fetchAll(); $i++; } } catch(PDOException $e) { echo $e-&gt;getMessage(); } </code></pre> <p>However, I keep getting a syntax error. The error goes away if I try it in the following way, but this way is not very useful to me because it does not avoid SQL injections.</p> <pre><code>try { $i = 0; while($i &lt; $A) { $STH = $DBH-&gt;query('SELECT * FROM ' .$tables[$i]); $result[$i] = $STH-&gt;fetchAll(); $i++; } } catch(PDOException $e) { echo $e-&gt;getMessage(); } </code></pre> <p>Although this last method works, from my understanding it does not help with mitigating SQL injection. And a secondary issue I'm running across is that sometimes these tables will not exist and my workaround for these issues in the old method was to do a small check:</p> <pre><code>$result_cc = mysql_query($sql_cc); if(mysql_num_rows($result_cc) != 0){} </code></pre> <p>However, this intermediate step seems to be gone in PDO, so I still need to figure out how to check for this.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload