我在程序中有以下代码,但是当我以'index.php'的形式包含'errors.php'时,它给我一个错误。我以前曾经使用过它,但从未遇到过这个错误,所以我对这个错误感到困惑。这是我的代码:
index.php
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Título</label>
<input type="title" name="title" value="">
</div>
<div class="input-group">
<label>Difficulty</label>
<select name="difficulty" id="difficulty">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<br>
<div class="input-group">
<label>Solución</label>
<textarea name="solution" rows="4" cols="55"></textarea>
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_exercise">Add</button>
</div>
</form>
errors.php
<?php
if (isset($_SESSION["errors_reg"])) {
$errors = $_SESSION["errors_reg"];
$_SESSION["errors_reg"] = null;
}
?>
<?php
if (isset($_SESSION["errors_student"])) {
$errors = $_SESSION["errors_student"];
$_SESSION["errors_student"] = null;
}
?>
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
<?php
$errors = null;
?>
我在行<?php if (count($errors) > 0) : ?>
谁能告诉我为什么出现此错误?这是错误:
Warning: count(): Parameter must be an array or an object that implements Countable in C:wamp64wwwprojecterrors.php on line 15 <?php if (count($errors) > 0) : ?>
as $errors
仅在各种if
条件内设置,它不会总是创建。因此,首先将默认值设置为一个空数组,然后在每个点添加一个新错误,使用[]
...
<?php
$errors = [];
if (isset($_SESSION["errors_reg"])) {
$errors[] = $_SESSION["errors_reg"];
$_SESSION["errors_reg"] = null;
}
?>
警告清楚地指出,变量$errors
应为 array
或 object
,您需要更改代码
$errors[] = $_SESSION["errors_reg"];
和
$errors[] = $_SESSION["errors_student"];