PHP查询将无法正常工作

时间:2016-09-09 15:39:27

标签: php mysql pdo

这是我第一次使用编程,我无法解决这个问题。我在教程中找到了代码,但它对我不起作用。

列表不会显示来自数据库的数据,但是在表格中它都可以正常工作。

Image

我的代码:

<?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>";
?>

1 个答案:

答案 0 :(得分:0)

仅供记录。 PDO是一个很好的扩展,可以使您的代码显着缩短。它可以为你做很多事情。但是很多教程都会教你重新发明已经存在于PDO中的很多轮子。如果把所有的垃圾拿走,你会发现PDO实际上是在给你最干净的代码:

<?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>";

其余部分由PDO处理