简体   繁体   中英

MySQL doesn't output PHP query result

I wrote this simple script based on my database table (db_member) with an auto incrementing row I'd and some other columns: 1: 'privilege' column, privilege values can be one of 'A', 'B' or 'C'.

2: 'username' column, for respective usernames

Objective: Output the 'username' on a row where the 'privilege' value is 'A'. There's only one such row in the database.

Environment: Windows 7 Ultimate. XAMPP 1.8.2. The XAMPP installation has Apache 2.4.10, MySQL 5.4.39, PHP 5.4.31. Dreamweaver CS6 and Mozilla Firefox,

Observation: The script runs in the browser. However, the exact space for the script turns up empty even in firefox source code. Neither a result nor an error.

Been hammering my head against this for two weeks now. And yes.... I have searched the web to no avail.

Script:

  <?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>

You have not collected mysql_fetch_array($result); result in $row

$row= mysql_fetch_array($result);

You have 2 issues with your script

  1. You need to remove extra single quote after opening php tag at the first line

     <?php' 
  2. Before using $row, you need to assign it a value:

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

    Note: The code above shall only load one row from database, if you want to load multiple rows, then you need to use WHILE loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM