html代码中的SELECT查询没有结果

时间:2017-09-11 22:04:16

标签: php html

我正在尝试在html文件中安装php代码,该代码将通过使用SELECT查询来呈现所有俱乐部朋友。无法在页面内看到结果。需要帮忙。这里是整个PHP代码(和一些html)集成的内部html:

<h2> Club Members</h2>
<br/>
<table dir="ltr" align="center" border="1">
<tr>
<td><b>Private Name</b></td>
<td><b>Family Name</b></td>
<td><b>E-mail</b></td>
  </tr>

   <?php

// Create connection
$conn = mysqli_connect('localhost','root',"");

//Check if the connection was opened, if not prompt the error to the page.
if (!$conn)
{
  die('Could not connect: ' . mysqli_error());
}

//Select the data base.
mysqli_select_db($conn, "Club");

//Set the character set to utf-8 to allow hebrew.
mysqli_query($conn, "SET NAMES 'utf8'");

//SQL query - user Details  
    $sql = "SELECT Fname, Lname, Mail FROM customers";
    $result = mysqli_query($sql);
    while($row = mysqli_fetch_array($result))
    {
    ?>
<tr>
<td><?php echo $row["Fname"] ?></td>
<td><?php echo $row["Lname"] ?></td>
<td><?php echo $row["Mail"] ?></td>
</tr>
    <?php
    }
?>
</table>

感谢。

2 个答案:

答案 0 :(得分:1)

我认为您错过了将连接链接变量包含在查询和错误函数中。 e.g。

$result = mysqli_query($sql);
die('Could not connect: ' . mysqli_error());

VS

$result = mysqli_query($conn, $sql);
die('Could not connect: ' . mysqli_error($conn));

答案 1 :(得分:-1)

我已经在MySQLi面向对象 中重写了您的代码,但我强烈建议使用PHP PDO来获得更快,更可靠的解决方案

只需用下面的代码替换旧代码即可。

<h2> Club Members</h2>
<br/>
<table dir="ltr" align="center" border="1">
<tr>
<td><b>Private Name</b></td>
<td><b>Family Name</b></td>
<td><b>E-mail</b></td>
  </tr>
<?php
//recoded in MySQLi Object-oriented by Ajmal PraveeN
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "Club";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_query($conn, "SET NAMES 'utf8'");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM customers";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row["Fname"]; ?></td>
<td><?php echo $row["Lname"]; ?></td>
<td><?php echo $row["Mail"]; ?></td>
</tr>
<?php
    }
} else {
    echo "0 results";
}
echo '</table>';
$conn->close();
?>