我正在尝试将 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/