PHP不在网站上显示数据库

时间:2017-03-14 15:27:08

标签: php html

我已经编译了以下PHP和HTML,我想要做的是将我的WAMP数据库连接到我的网页,这是一个简单的任务,但我收到的输出显示在下面的图片中,有人可以告诉我哪里出错了?

<?php
    //Step 1
    $db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');
?>

<html>
    <head>
    </head>
    <body>
        <h1>
            PHP connect to MySQL
        </h1>
        <?php
            //Step 2
            $query = "SELECT * FROM patients";
            mysqli_query($db, $query) or die('Error querying database.');

            $result = mysqli_query($db, $query);
            $row = mysqli_fetch_array($result);

            while($row = mysqli_fetch_array($result)){
                echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
            }
        ?>
    </body>
</html>

PHP and HTML error

2 个答案:

答案 0 :(得分:1)

我在该代码中发现了一些错误

$query = "SELECT * FROM patients";

您需要在此处添加分号到查询代码的末尾,所以:

$query = "SELECT * FROM patients;";

然后我们有了这个

$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);

while($row = mysqli_fetch_array($result)){
   echo $row['id'] . ' ' . $row['patient_name']. ' ' . $row['check_in_date'] . ' ' . $row['room_number'] . ' ' . $row['bed_number'] . ' ' . $row['notes'] . '<br />';
 }

这应该有效

$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
   $id = $row['id'];
   $patientname = $row['patient_name']; //do this with every variable you have
   echo "$id $patientname";
}

编辑:另外,更改此

$db = mysqli_connect('localhost', 'root', '', 'hospital') or die('Error connecting to MySQL server.');

用这个

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hospital";
$db = mysqli_connect($dbhost,$dbuser,$dbpass) or die ("dbconn");
mysql_select_db($dbname,$db) or die ("msq");

答案 1 :(得分:0)

你不需要分配 $row = mysqli_fetch_array($result);因为你在while循环中分配它

编辑回答

从行构建一个sperate数组,然后循环遍历,这样你就可以更灵活地在显示结果之前添加或编辑结果

//Step 2
$query = "SELECT * FROM patients";
mysqli_query($db, $query) or die('Error querying database.');

$result = mysqli_query($db, $query);

$rows = array();
while($row = mysqli_fetch_array($result)){
    $rows[] = $row;
}

foreach($rows as $r) {
    echo $r['id'] . ' ' . $r['patient_name']. ': ' . $r['check_in_date'] . ' ' . $r['room_number'] . ' ' . $r['bed_number'] . ' ' . $r['notes'] . '<br />';
}