MsCrelix MsCrelix - 2 months ago 5
MySQL Question

PHP QUERRY Won't work

It's my first expierence with programming and I can't get trought this problem. I found code in tutorial, but it wont work for me.

List won't show data from database, but in Table it all works.

Image

My Code:

<?php

$servername = "111";
$username = "1111";
$password = "111";
$dbname = "1111";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "<select name='Choose Region'>";
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo "<option value='" . $v['Region_Namee'] ."'>" . $v['Region_Name'] ."</option>";

}
}

catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</select>";
?>

Answer

Just for the record. PDO is excellent extension that can make your code dramatically shorter. It can do a lot of things for you. But many tutorials will teach you to reinvent a lot of wheels already existing in PDO. If take all the rubbish out you'll see that PDO is actually giving you the cleanest code possible:

<?php
$servername = "111";
$username = "1111";
$password = "111";
$dbname = "1111";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// everything above this line should go into separate file
// and just gets included here

$stmt = $conn->query("SELECT Region_ID, Region_Name FROM Regions"); 
echo "<select name='Choose Region'>";
foreach ($stmt as $v) { 
    echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
echo "</select>";

the rest is handled by PDO

Comments