MySQL 不输出 PHP 查询结果

MySQL doesn't output PHP query result

我根据我的数据库 table (db_member) 编写了这个简单的脚本,其中包含一个自动递增的行和一些其他列: 1:'privilege'列,权限值可以是'A'、'B'或'C'之一。

2:'username' 列,对应用户名

Objective: 在 'privilege' 值为 'A' 的行上输出 'username'。数据库中只有这样一行。

环境: Windows7终极版。 XAMPP 1.8.2。 XAMPP 安装有 Apache 2.4.10、MySQL 5.4.39、PHP 5.4.31。 Dreamweaver CS6 和 Mozilla Firefox,

观察: 该脚本在浏览器中运行。但是,即使在 Firefox 源代码中,脚本的确切 space 也变成空的。既不是结果也不是错误。

两周来我一直在苦思冥想。是的......我已经在网上搜索无济于事。

脚本:

  <?php

  error_reporting(1);

  ?>
  <!doctype html>
  <html>
  <head>
  <meta charset="utf-8">
  <title>My site</title>
  </head>

  <body>
  <div id="container">
   <header>
   </header>
   <section>
  <h1>Testing, testing, 1, 2, 3.</h1>
   <?php

  $host = 'localhost';
  $user = 'dbuser';
  $password = 'userpass';
  $database_name = 'dbname';


  //Establish a connection with MySQL
  $db = mysql_connect($host, $user, $password) or
   die('<b>Sorry!<br>Unable to connect to the database .<br/>Please try later.</b>');

  //Ensure the correct database is accessed
  mysql_select_db($database_name, $db) or die(mysql_error($db));


   $query = 'SELECT * FROM db_members WHERE privilege = "A"';
  $result = mysql_query($query, $db) or die('Can\'t connect to database');

  mysql_fetch_array($result);
  if(mysql_num_rows($result) > 0)
  {
  echo $row['username'];
  }
  else{
  echo '<b>There\'s no result.</b>';
  }

 ?>
 </section>
</div><!--End of container-->
</body>
</html>

您还没有收集到mysql_fetch_array($result);结果为 $row

$row= mysql_fetch_array($result);

您的脚本有 2 个问题

  1. 您需要在第一行打开 php 标签后删除多余的单引号

    <?php'
    
  2. 在使用$row之前,需要给它赋值:

    $row = mysql_fetch_array($result);
    if(mysql_num_rows($result) > 0)
    {
      echo $row['username'];
    } else {
      echo '<b>There\'s no result.</b>';
    }
    

    注意:上面的代码只能从数据库中加载一行,如果要加载多行,则需要使用WHILE循环

    while ($row = mysql_fetch_array($result))
    {
      echo $row['username'];
    } else {
      echo '<b>There\'s no result.</b>';
    }