使用php在网页上显示数据库中的信息

时间:2014-10-27 23:39:55

标签: php mysql

尝试从网页中显示的数据库中获取信息。这是我的代码:

<body>
<?php
$con=mysqli_connect("localhost", "root", "");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

/*
$db_selected = mysqli_select_db("music" , $con);
*/

$strSQL = "SELECT * FROM music";

$rs = mysqli_query($strSQL, $con);

while($row = mysqli_fetch_array($rs, MYSQLI_BOTH)) {

   // Write the value of the column FirstName (which is now in the array $row)
  echo $row['artist'] . "<br />";
  echo $row['title'] . "<br />";
  echo $row['format'] . "<br />";
  echo $row['notes'] . "<br />";

  }
?> 

2 个答案:

答案 0 :(得分:6)

使用mysqli_,连接首先是一切。虽然连接是带有mysql_函数的最后一个参数,但您可能因为过去使用过mysql_函数而混淆了这些函数,并且现在决定开始使用mysqli_

让我们从您已注释掉的开始:

/*
$db_selected = mysqli_select_db("music" , $con);
*/

要么将其更改为:

$db_selected = mysqli_select_db($con, "music");

或改变:

$con=mysqli_connect("localhost", "root", "");

到:

$con=mysqli_connect("localhost", "root", "", "music");

正如我在下面那样使用一行中的所有四个参数。

重要的旁注:

确保数据库和表确实都称为music

如果您的数据库名称与music不同,那么您需要使用的是第四个参数,而不是表名。

<body>
<?php
$con=mysqli_connect("localhost", "root", "", "music");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$strSQL = "SELECT * FROM music";

$rs = mysqli_query($con, $strSQL);

while($row = mysqli_fetch_array($rs, MYSQLI_BOTH)) {

   // Write the value of the column FirstName (which is now in the array $row)
  echo $row['artist'] . "<br />";
  echo $row['title'] . "<br />";
  echo $row['format'] . "<br />";
  echo $row['notes'] . "<br />";

  }
?> 

使用or die(mysqli_error($con))mysqli_query()会发出错误信号。

更准确地说:

$rs = mysqli_query($con, $strSQL) or die(mysqli_error($con));

答案 1 :(得分:1)

你并没有真正要求的东西,但问题的答案是:

将此行更改为:

$con=mysqli_connect("localhost", "root", "","music"); // If the db is called music

并且您需要将此行/变量放在另一个方向:

$rs = mysqli_query($strSQL, $con);

需要:

$rs = mysqli_query($con, $strSQL);

并在select语句中放入正确的表,然后它就可以了。