php - How to append data obtained from database to array?
问题描述
I would like to append data("username") from database to array("array1") and write all items from array. I have marked problematic part of code. If I run this code, I see: What can be wrong?
Output
Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array,
data_to_array.php
<?php
$conn = mysqli_connect("localhost", "root", "", "company");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// problematic function append from there
$array1 = array();
while ($row = $result->fetch_assoc()) {
array_push($array1, ["username"]);
}
for ($x = 0; $x != count($array1); $x++) {
echo $array1[$x].", ";
}
// to there
} else {
echo "0 results";
}
$conn->close();
解决方案
尝试这个:
while($row = $result->fetch_assoc()) {
array_push($array1, $row["username"]);
}
您还可以使 for 循环更整洁:
foreach($array1 as $item) {
echo $item . ',';
}
在您的原始代码中,您将一个带有“用户名”的数组插入到您的 $array1中,
写作['foo']
方式与array('foo');
推荐阅读
- angular - 为什么在检查单个复选框时检查列的所有复选框 - Angular table
- python - 从临时文件夹写入存储是否有任何时间延迟或限制?
- rxjs - 从 RxJs 中的 Observable 中提取一个值
- google-cloud-platform - Google-cloud-PubSub 是否支持 amqp 1.0 协议?
- talend - 无法动态加载上下文变量
- node.js - 在 mogodb-nodejs 驱动程序中查找同一集合中的不同文档
- python - 如何将 Json 数据存储在复杂的 Python 列表中
- c# - 使用newtonsoft json C#序列化对象的大列表
- css - 删除 Vuetify v-app-bar 上的默认填充
- mysql - 根据列值连接 3 个表 - Laravel