I have some working code that uses a SQL select statement within it. As a static bit of code, it works great, however, I want to be able to use variables in it. So, doing my research, everyone says you should use PHP Prepare statements, to keep things safe and secure. So, my old code looks something like this:
/*** MY OLD WORKING CODE ***/
/*** SQL Query ***/
$sql = "SELECT tickets.ref AS `Ticket Number` ......
.....BLAH................INTERVAL 30 DAY) AND
organizations.name = 'NAMEIWANTTOUSE' ";
/*** For Each Loop to Build Table ***/
foreach ($dbh->query($sql) as $row){
echo "<tr>";
echo "<td bgcolor=89FF95 align=center>".$row['Ticket Number']."</td>";
ETC..................
}
$sql->closeCursor();
My new code, that Im trying to get working.. seems to be doing nothing. I know Im not too far out with it, but I just cant get to grips with which variable I should be pushing into my FOREACH loop.. or if I have actually got the PHP Prepare statement right at all?
Any suggestions anyone?
/*** MY NEW NOT WORKING CODE ***/
/*** Variables ***/
$NAME = 'NAMEIWANTTOUSE';
$DAYS = '30';
/*** Prepare the SQL Query ***/
$stmt = $sql->prepare("SELECT tickets.ref AS `Ticket Number` .......
....BLAH................INTERVAL :DAYS DAY) AND
organizations.name = :NAME ");
$stmt->bindParam(":DAYS", $DAYS);
$stmt->bindParam(":NAME", $NAME);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
/*** Put each return from SQL into a Variable? ***/
$MySQLQuery = $stmt->fetchAll();
/*** For Each Loop to Build Table ***/
foreach ($dbh->query($MySQLQuery) as $row){
echo "<tr>";
echo "<td>".$row['Ticket Number']."</td>";
ETC..................
}
$sql->closeCursor();
Thanks
You nearly do have it, except that you ought not be calling
query()in the loop. The result set has already been fetched into$MySQLQuery.fetchAll()returns a 2D array, unlike the oldmysql_query()which returned a result resource that needed to be looped over withmysql_fetch_*().