php - 如何从 pdo 语句显示数组的所有值?

标签 php html mysql arrays pdo

我正在尝试将 PDO 语句中的各个值显示到单选按钮。 这是我目前所拥有的。

    <?php

    session_start();  
    $host = "localhost";  
    $username = "root";  
    $password = "";  
    $database = "training";  
    $result = "";

        $connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);  

            $query = "SELECT username FROM accounts";  
            $statement = $connect->prepare($query);
            $statement->execute();
            $result = $statement->fetchAll(PDO::FETCH_ASSOC);  

    echo "<input type='radio' name ='president'>". $result . "</input>"

    ?>

但结果是这样

"Notice: Array to string conversion in C:\xampp\htdocs\testing\vote.php"

我试过使用 print_r($result); 来检查值

[0] = admin
[1] = operation1

我希望这些值显示在单选按钮文本上。

最佳答案

您收到通知是因为您尝试使用 echo 打印数组而不是数组元素。

您正在使用 fetchAll()。所以,$result 数组是一个二维数组。像这样:

Array
(
    [0] => Array
        (
            [username] => John
        )

    [1] => Array
        (
            [username] => Mikaela
        )

    [2] => Array
        (
            [username] => Angela
        )
)

它应该是这样的:

// Fetch the values.
$query = "SELECT username FROM accounts";  
//...
$result = $statement->fetchAll(PDO::FETCH_ASSOC);

/*
 * Just for testing: display results.
 * Note: In the future use this complete line to display an array, if you want to.
 */
echo '<pre>' . print_r($result, TRUE) . '</pre>';

/*
 * Print the radio buttons.
 * Note: Note: Apply apostrophe (') and double quote (") like this.
 */
foreach ($result as $key => $item) {
    $username = $item['username'];
    echo '<input type="radio" name="president" value="' . $username . '">' . $username . '</input>';
}

尝试使用异常处理。要正确使用带有异常处理的准备好的语句,请参阅 this answer of mine (查看 Add.php(类))。

祝你好运!

关于php - 如何从 pdo 语句显示数组的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987949/

相关文章:

php - 如何根据 MySQL 表单元格的值执行 IF 语句?

php - PHP 运算符 =& 是什么意思?

php - 来自 php 变量的 Google Analytics 自定义变量(动态数字)

javascript - Javascript遗留的噩梦-试图绕过一些压缩的JavaScript

html - 如果页面宽度大于我的屏幕,我如何绝对定位?

php - 扩展 Doctrine 对象类

mysql - max 函数内的 SQL 比较

mysql - 与 mysql 相同的 Firebird 数据库表中的最大记录数?

php - 更改发送到 gmail 或 hotmail 的默认 laravel 电子邮件模板主题

javascript - html 中的 <a> 标签