douai2499 2016-09-09 15:39 采纳率: 100%
浏览 9
已采纳

PHP查询将无法正常工作

It's my first experience with programming and I can't solve this problem. I found code in tutorial, but it won't 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>";
?>
  • 写回答

1条回答 默认 最新

  • dq13733519262 2016-09-09 15:55
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面