I am new to PDO, really new, I'm trying to read documentation from several site (this, for example) but I just don't fully understand it.
Still, I wish to update an internal website I'm using in my company because this project is becoming bigger and important and I want to rewrite it to shape it better.
I was able to "convert":
<?php
$sql = "SELECT name FROM table order by name ASC";
$result1 = pg_query($conn, $sql);
while ($row = pg_fetch_row($result1)) {
echo "<option value='$row[0]'>$row[0]</option>";
}
?>
to:
<?php
$sql = "SELECT name FROM table order by name ASC";
$stmt_menu = $pdo->prepare($sql);
$stmt_menu -> execute();
foreach ($stmt_menu as $row){
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
?>
Even though I would have preferred to continue using the row[0]
for simplicity, but Apache's logs complained about PHP Notice: Undefined offset: 0 in /var/www/pdo-test-website/left-menu.php on line 20
Following other tutorials (like this one), I am trying to replace the current datalist SQLs into a PDO based statements.
Before I had:
<input type="text" list="test_list" class="form-control input-sm" name="test_name" id="test_name_id" />
<?php
echo '<datalist id="test_list">';
$test_name = pg_query("SELECT DISTINCT ON (FOO) FOO FROM table;");
while ($row = pg_fetch_row($test_name)) {
echo "<option value='$row[0]'>$row[0]</option>";
}
echo '</datalist>';
?>
Now:
<?php
$datalist_foo = "SELECT DISTINCT ON (:value) :value FROM table;";
$stmt_datalist = $pdo->prepare($datalist_foo);
echo '<datalist id="test_list">';
$stmt_datalist->execute(['value' => "FOO"]);
foreach ( $stmt_datalist as $row ) {
echo "<option value=".$row['FOO'].">".$row['FOO']."</option>";
}
echo '</datalist>';
?>
I am trying my best to have it working but I keep reading errors in the Apache's error log file. I tried rewriting this statement in many different versions, it would be not so useful if I would paste the log file for your reviewing because I should also write, for each error row, its full php code.
The last error, the one that I get after trying the code I posted above, is:
PHP Notice: Undefined index: FOO in /var/www/pdo-test-website/datalist.php
I just want to note, that the non-pdo version works, the (test) database have data inside and I am able to fetch them using the "old" pg_query method.
I hope you can give me some advice, I also tried the solution at this link: returning multiple rows from postgre PDO but I can't get it working.