如何解决PHP无法从mysql数据库获取数据的问题?

时间:2019-07-20 10:59:08

标签: php mysql mysqli

enter image description here

我正在一个帖子共享网站上,我需要从我的MySQL数据库“ mugg_website”中收集帖子的标题。在编写完PHP代码,在MySQL数据库上创建帖子并使用WAMP运行它之后,没有标题,需要显示在首页上。

我的代码(mugg.php):

<?php
    require_once("connection.php");
?>

<!doctype html>
<html>
    <head>

        <meta charset="utf-8">
        <title>mugg. | Pradinis</title>
        <link>
    </head>

    <body>
        <div class="header">
            <h2>mugg.</h2>
        </div>
        <div class="menu">
            <a href="index.php">Pagrindinis</a>
            <a href="#">Pasiekite mus</a>
        </div>
        <div class="content">
            <?php 
                $q='SELECT `id`, `post_title` FROM `post` WHERE `status`="paskelbta"';
                $r=mysqli_query($con, $q);
                if($r){
                    if(mysqli_num_rows($r) > 0){
                        while($row = mysqli_fetch_assoc($r)){
                            $id = $row['id'];
                            $post_title = $row['post_title'];

                            echo '<a href="?id='.$id.'">'.$post_title.'</a>';
                        }
                    }else{
                        echo 'no post';
                    }
                }else{
                    echo $q;
                }
            ?>
        </div>
    </body>
</html>

(connection.php):

<?php
    $con = new mysqli_connect("localhost", "root", "", "mugg_website");
?>

1 个答案:

答案 0 :(得分:-1)

更改

<?php
$con = new mysqli_connect("localhost", "root", "", "mugg_website");
?>

<?php
$con = mysqli_connect("localhost", "root", "", "mugg_website");
?>

并在连接错误的情况下添加错误消息。

// Check connection

    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }