PHP PDO从mysql获取数据并回显它们

时间:2020-09-17 02:40:43

标签: php mysql

我知道这对某些人来说将非常容易,但是我对这个话题还很陌生。我正在尝试从我的数据库中读取以下HTML值,以获取一个普通的HTML页面,该页面应从数据库中获取这些值,而不必在HTML中进行更改。 整个过程不应在表中发生,而应通过ECHO在不同区域中简单地输出值。

以我的代码为例,我做了什么,但是坚持只回显值。

    $sth = $conn->prepare("SELECT text_beschreibung FROM magical_moments_text");
    $sth->execute();

    $result = $sth->fetchAll(\PDO::FETCH_NUM);
    var_dump($result);

结果是这个

    array(3) { 
        [0]=> array(1) {
             [0]=> string(2) "33" 
        } 
        [1]=> array(1) {
             [0]=> string(3) "555" 
        } 
        [2]=> array(1) { 
            [0]=> string(3) "444" 
        } 
    }  

现在出现了我不知道下一步该怎么做的部分。我不想输出var_dump,而只输出“”中的值。但是整个事情应该像这样

echo $result[1]; 

对于最后一个例子,我的意思是我想这样解释它

<?php
$sth = $conn->prepare("SELECT text_beschreibung FROM magical_moments_text");
$sth->execute();

$result = $sth->fetchAll(\PDO::FETCH_NUM);
    
?>
<html>
    <body>
        <p>The following code should give me <?php echo $result[0]; //33 ?></p>     
        <p>The following code should give me <?php echo $result[1]; //555 ?></p>        
        <p>The following code should give me <?php echo $result[2]; //444 ?></p>        
    </body>
</html>

如果我使用这种方法,它将给我这个

Notice: Array to string conversion in

希望我解释得足够好。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

通常我会做这样的事情

$qry = "SELECT text_beschreibung FROM magical_moments_text";
$stmt = $conn->prepare($qry); # good practice on using prepared stmt
$stmt->execute();
$result = $stmt->get_result();

然后循环$ result

while ($row = $result->fetch_assoc()) {
    echo("<p>The following code should give me ". $row['text_beschreibung'] ."</p>");
}
相关问题