当我使用此代码时。它说:
数据库访问失败:未选择数据库"
它还给出了:
不推荐使用:mysql_query():不推荐使用mysql扩展名 将来删除:使用mysqli或PDO代替
错误。以下是我使用的代码。
$con = mysqli_connect("localhost", "root", "","radian")
or die ("Couldn't connect to mySQL");
$query = "SELECT Staff_id,Fname,Sname,Gender,username FROM staff ";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_array($result);
$staff_id = $row['Staff_id'];
$Fname = $row['Fname'];
$Sname = $row['Sname'];
$Gender = $row['Gender'];
$username = $row['username'];
echo '<tr> <td>'.$staff_id.'</td> <td>'.$Fname.'</td> <td>'.$Sname.'</td> <td>'.$Gender.'</td> <td>'.$username.'</td> </tr>';
}
它说错误来自这一行:
$result = mysql_query($query);
答案 0 :(得分:0)
您使用 mysql 代替 mysqli ,而mysqli需要与查询建立连接。
只需用以下代码替换您的代码:
$con = mysqli_connect("localhost", "root", "","radian")
or die ("Couldn't connect to mySQL");
$query = "SELECT Staff_id,Fname,Sname,Gender,username FROM staff ";
$result = mysqli_query($con, $query);
if (!$result) die ("Database access failed: " . mysqli_error($con));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_array($result);
$staff_id = $row['Staff_id'];
$Fname = $row['Fname'];
$Sname = $row['Sname'];
$Gender = $row['Gender'];
$username = $row['username'];
echo '<tr> <td>'.$staff_id.'</td> <td>'.$Fname.'</td> <td>'.$Sname.'</td> <td>'.$Gender.'</td> <td>'.$username.'</td> </tr>';
}
答案 1 :(得分:0)
你混合了mysql / mysqli。
$con = mysqli_connect("localhost", "root", "","radian");
if(!$con)
{
exit("Couldn't connect: ".mysqli_connect_error());
}
mysqli_set_charset($con, "utf8");
echo "<table>";
echo "<tbody>";
$query = "SELECT Staff_id,Fname,Sname,Gender,username FROM staff";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result))
{
$staff_id = $row['Staff_id'];
$Fname = $row['Fname'];
$Sname = $row['Sname'];
$Gender = $row['Gender'];
$username = $row['username'];
echo '<tr><td>'.$staff_id.'</td><td>'.$Fname.'</td><td>'.$Sname.'</td><td>'.$Gender.'</td><td>'.$username.'</td></tr>';
}
echo "</tbody>";
echo "</table>";
答案 2 :(得分:0)
您正在使用 mysqli
构建数据库连接$con = mysqli_connect("localhost", "root", "","radian")
or die ("Couldn't connect to mySQL");
在您的查询中,您使用 mysql ,您需要在查询中使用 mysqli ,而不是使用 mysql
$query = "SELECT Staff_id,Fname,Sname,Gender,username FROM staff ";
$result = mysqli_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_array($result);
$staff_id = $row['Staff_id'];
$Fname = $row['Fname'];
$Sname = $row['Sname'];
$Gender = $row['Gender'];
$username = $row['username'];
echo '<tr> <td>'.$staff_id.'</td> <td>'.$Fname.'</td> <td>'.$Sname.'</td> <td>'.$Gender.'</td> <td>'.$username.'</td> </tr>';
}