php - 如何修复警告:为 foreach() 提供的参数无效
问题描述
我正在使用 PHP 在本地计算机上设置编辑用户页面。有这个错误
<?php foreach ($user as $key => $value) : ?>
警告:在第 79( )行为 foreach() 提供的参数无效
我试图解决它,但徒劳无功。我对 PHP 有点陌生。也许有些东西我错过了或没有看到。如果需要,请协助和纠正我。以下是来自 update.php 页面的代码。
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
include_once 'core/init.php';
require 'common.php'; //Escapes HTML for output
if (isset($_POST['submit'])) {
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$user = [
"id" => $_POST['id'],
"username" => $_POST['username'],
"email" => $_POST['email'],
"join_date" => $_POST['join_date']
];
$DB->query ('UPDATE users
SET id = :id,
username = :username,
email = :email,
join_date = :join_date
WHERE id = :id');
$DB->execute();
}
catch(PDOException $e){
echo $this->error = $e->getMessage();
}
}
if (isset($_GET['id'])) {
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$id = $_GET['id'];
$DB->query('SELECT * FROM users WHERE id = :id');
$DB->bind(':id', $id);
$DB->execute();
$result=$DB->resultset();
// Catch any errors
}
catch(PDOException $e){
echo $this->error = $e->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $DB) : ?>
<blockquote><?php echo escape($_POST['username']); ?> successfully updated.</blockquote>
<?php endif; ?>
<h2>Edit a user</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?></label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?> >
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
<a href="http://localhost/form/home.php">Back to home</a>
<?php include "templates/footer.php"; ?>
解决方案
您没有为变量 $user 的初始加载设置任何值,因此它在 中未定义foreach
,因此请使用
$user = [];
if (isset($_POST['submit'])) {
try{
或检查并设置 $user 的值
<?php foreach ($user ?? [] as $key => $value) : ?>
推荐阅读
- python - Python - 从索引值中删除引号
- flutter - FakeAsync 和 quiver.testing.async 有什么区别?
- c# - Unity 2019.2.11f1 中的所有代码命令是否有字典或摘要?
- c++ - C++ 指针在 for 循环中被覆盖
- nginx - 如何配置 nginx 部署以将流量传递到 Google Kubernetes Engine 中的前端部署?
- swift - 为 imageview 创建通用变量以添加 uipangesture
- python - 理解困难
- java - 是否可以看到 Jackson Annotations 创建的 JSON?
- python - 使用 Pandas isin() 和 merge() 对数据框进行子集化的区别
- java - 如何按列表描述的顺序有效处理 HashMap?