我正在尝试以样式方式从数据库输出所有数据。但是,它似乎并不符合要求。这是代码:
我试图输出的方式:
<?php
include 'database.php';
$sql = "SELECT * FROM patients";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='titleBox'>ID: " . $row["id"]. " : First Name : " . $row["fname"]. " : Last Name : " . $row["lastname"] . " : Age : " . $row["age"] . "</div><br>";
echo "<div class='titleBox'>Description: " . $row["descript"] . "</div><br>";
}
} else {
echo "<div class='titleBox'>No patients on record.</div>";
}
$conn->close();
?>
连接数据库:
<?php
$server = "localhost";
$username = "root2";
$password = "passwordking";
$db = "root2";
try{
$conn = new PDO("mysql:host=$server;dbname=$db;", $username, $password);
} catch(PDOException $e){
die( "<div class='titleBox'>Connection failed: " . $e->getMessage() . "</div>");
}
编辑:很抱歉&#39;回合。没有任何输出。
答案 0 :(得分:1)
你需要告诉我们你得到了什么错误或者脚本有什么问题。
首先,正如Alton在评论中指出的那样,你正在混合PDO和mysqli。你需要坚持一个。让我们以mysqli为例。
your database.php
<?php
$server = "localhost";
$username = "root2";
$password = "passwordking";
$db = "root2";
$conn = new mysqli($server, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
然后将num_rows保存在变量中并检查它是否&gt; 0
<?php
include 'database.php';
$sql = "SELECT * FROM patients";
$result = $conn->query($sql);
$rows_num = $result->num_rows; #store the number of rows
#use it in if statement
if ($rows_num > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='titleBox'>ID: " . $row["id"]. " : First Name : " . $row["fname"]. " : Last Name : " . $row["lastname"] . " : Age : " . $row["age"] . "</div><br>";
echo "<div class='titleBox'>Description: " . $row["descript"] . "</div><br>";
}
} else {
echo "<div class='titleBox'>No patients on record.</div>";
}
$conn->close();
?>