如果没有记录与查询匹配,则隐藏SELECT查询的结果

时间:2014-02-28 04:02:51

标签: php mysql

<?php $theplayer = ruthbabe01; ?>
<?php
    mysql_connect("server", "user", "password");
    mysql_select_db("database");

    $sql = mysql_query("SELECT playerID,games FROM HittingStreaks WHERE playerID = '$theplayer' ORDER BY games DESC ");

    echo "<h3>Hitting Streaks</h3>";

    while($row = mysql_fetch_array($sql)){
      $playerID = $row['playerID'];
      $games = $row['games'];

    echo "$playerID ... $games<br />";

}
?>

一个简单的小SELECT查询,但如果没有与查询匹配的记录,我不希望看到echo "<h3>Hitting Streaks</h3>";或其他echo "$playerID ... $games<br />";。换句话说,如果该播放器($theplayer)在表中没有记录,则不执行任何操作。不要回显任何HTML。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

切换到MySQLi因为我不打算推​​荐使用不推荐使用的库的解决方案,只需使用mysqli_stmt::$num_rows属性即可。您还应该使用预准备语句并将$theplayer值绑定为参数。例如......

<?php
// remove these two lines once you've finished development
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$theplayer = 'ruthbabe01';

$con = new mysqli('server', 'user', 'password', 'database');
if ($con->errno) {
    throw new Exception($con->error, $con->errno);
}
$con->set_charset('utf8');

$stmt = $con->prepare('SELECT playerID, games FROM HittingStreaks WHERE playerID = ? ORDER BY games DESC');
if (!$stmt) {
    throw new Exception($con->error, $con->errno);
}

$stmt->bind_param('s', $theplayer); // FYI VARCHAR keys are a terrible idea

if (!$stmt->execute()) {
    throw new Exception($stmt->error, $stmt->errno);
}

// need to call this to buffer the result in order to count the rows
$stmt->store_result(); 

$stmt->bind_result($playerID, $games);

if ($stmt->num_rows) : ?>

    <h3>Hitting Streaks</h3>

    <?php while ($stmt->fetch()) : ?>
        <?= htmlspecialchars($playerID) ?> ... <?= htmlspecialchars($games) ?><br>
    <?php endwhile ?>

<?php endif ?>

答案 1 :(得分:0)

使用以下代码:

<?php
  mysql_connect("server", "user", "password");
  mysql_select_db("database");
  $sql = mysql_query("SELECT playerID,games FROM HittingStreaks WHERE playerID = '$theplayer' ORDER BY games DESC ");
  $rows = mysql_num_rows($sql);
  if($rows>0) {
     echo "<h3>Hitting Streaks</h3>";
     while($row = mysql_fetch_array($sql)){
        $playerID = $row['playerID'];
        $games = $row['games'];
        echo "$playerID ... $games<br />";
     }
  }
?>

答案 2 :(得分:-1)

如果你不想获得row_num等等,你可以试试这个。

$needToPrint=true;
while($row = mysql_fetch_array($sql)){
  if($needToPrint)
  {
    echo "<h3>Hitting Streaks</h3>";
    $needToPrint = false;
  }
  $playerID = $row['playerID'];
  $games = $row['games'];

  echo "$playerID ... $games<br />";
}