-1

再会!我对 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>
4

1 回答 1

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']); 
}
于 2013-08-10T02:38:32.567 回答