I want to run a query using PDO based on the data in the URL parameter (yes, I know this is prone to attacks, but its internal code for the utility).
$user = 'USER'; $pass = 'PASSWORD'; $dsn = 'mysql:dbname=PRODUCTS;host=HOST'; try { $productDB = new PDO($dsn, $user, $pass); $productDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { $msg = 'PDO ERROR' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage(); die($msg); } if(isset($_GET['cat'])) { $cat = $_GET['cat']; print "cat = $cat <br>"; $products = $productDB->prepare('SELECT * FROM products WHERE cat_id LIKE ?'); $products->execute(array($cat)); $rows = $products->rowCount(); print "$rows rows returned"; ?> <table border="1"> <tr> <td>product_id</td> <td>product_name</td> </tr> <?php foreach ($products->fetchAll() as $row) { $id = $row['product_id']; $product_name = $row['product_name']; print "<tr>"; print "<th scope=\"row\"><b>$id</b></th>"; print "<td> $product_name </td>"; print "<tr>"; } print "</table>"; } ?>
When I run this code, it prints the correct number of lines depending on the query, but does not populate the table.
I also tried replacing the prepare and execute lines with:
$products = $productDB->query("SELECT * FROM products WHERE cat_id LIKE $cat");
Returns the correct row counter, but does not help.
And finally, I tried replacing the foreach string with something like:
$rows = $products->fetchAll(); foreach ($rows as $row) {
My attempts to do the same with a fixed query all work fine, but I am having problems with how to put a variable element in a query and then iterate over the results.
source share