我想为我的数据库选择最后一行,并将标题为s1和s2的列回显到网页正文,以下是我的代码。这会产生错误。
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb2";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
$row = array();
$row = mysqli_query($conn,$sql);
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
?>
</body>
</html>
答案 0 :(得分:1)
您必须使用mysqli_fetch_assoc(将遍历结果集),如下所示:
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
}
/* free result set */
mysqli_free_result($result);
}
没有循环:
if ($result = mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
if($row)
{
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
}
/* free result set */
mysqli_free_result($result);
}
答案 1 :(得分:0)
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb2";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("MySQL Connection Error"); // Try not to output SQL error messages on the front-end, look into error_reporting()
}
$sqlQuery = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
$results = mysqli_fetch_assoc(mysqli_query($conn, $sqlQuery));
echo " cup 1". $results["s1"]. "CUP 2". $results["s2"];
?>
</body>
</html>
除此之外,我建议不要在程序风格和面向对象的风格中进行SQL操作,因为这可能导致将来出现许多复杂情况。
答案 2 :(得分:0)
使用mysqli_fetch_assoc将结果提取到数组
$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
if ($result = mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
}