美好的一天! 我是PHP的新手,非常感谢你的任何帮助。
我想删除数据库中的一行,但是我收到了这个错误:
Warning: Illegal string offset 'text' in C:\xampp\htdocs\php\deletejoke\jokes.php on line 14
代码似乎还可以,但我不知道为什么我会收到这个错误。请指导我这个,非常感谢! 请参阅以下代码供您参考:
if (isset($_GET['deletejoke'])) {
try {
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error = 'Error deleting joke' . $e->getMessage();
include 'error.php';
exit();
}
header('Location: .');
exit();
}
try {
$sql = 'SELECT id, joketext FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.php';
exit();
}
foreach ($result as $row) {
$jokes = array('id' => $row['id'], 'text' => $row['joketext']);
}
include 'jokes.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise #3: Display contents from database</title>
<meta charset="utf-8"/>
</head>
<body>
<a href="?addjoke">Add your own joke!</a>
<p>Here are all the jokes in the database:</p>
<?php foreach($jokes as $joke): ?>
<form action="?deletejoke" method="post">
<blockquote>
<p>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>
<input type="hidden" name="id" value="<?php echo $joke['id']; ?>">
<input type="submit" value="Delete">
</p>
</blockquote>
</form>
<?php endforeach; ?>
</body>
</html>
答案 0 :(得分:1)
Warning
告诉您它正在处理$jokes
,因此将$joke
视为字符串而不是数组。
尝试像这样构建$jokes
数组
// initialize the array
$jokes = array();
foreach ($result as $row) {
// add to the array using $jokes[]
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}