我正在使用PHP在本地计算机上设置一个编辑用户页面。出现此错误
警告:第79行{
<?php foreach ($user as $key => $value) : ?>
)的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"; ?>
答案 0 :(得分:1)
您没有为变量$ user设置任何初始加载值,因此在foreach
中未定义该值,因此请使用
$user = [];
if (isset($_POST['submit'])) {
try{
或者检查并设置$ user的值
<?php foreach ($user ?? [] as $key => $value) : ?>