从数据库中删除行条目


DELETE row entry from database

您好!我是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>

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']); 
}