PHP条件总记录

时间:2013-06-21 20:42:34

标签: php html conditional-statements

我正在开发一个简单的条件,我只想在记录集的总行数大于1时显示HTML代码。 HTML内容未显示,可能是最佳条件选项?

mysql_select_db($database_connection, $connection);
$query_user = sprintf("SELECT * FROM users WHERE id = %s", GetSQLValueString($colname_user, "int"));
$user = mysql_query($query_user, $connection) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);

<?php
if ($totalRows_user > 1) {
    ?>
 <a href="excluiru.php?id=<?php echo $row_user['id']; ?>">
<img src="imagens/delete.png" alt="Remover" onClick="return confirm('Do you really want to delete this User?');" /></a>Delete User
      <?php 
    } ?>

更新:我发现mysql_num_rows($user);始终给出零值。 还有另一种计算方法吗?

我发现并解决了问题:D

<?php
$isExist = mysql_query("select COUNT(id) from users");
$r = mysql_fetch_array($isExist);
if($r['COUNT(id)'] > 1){
    ?>

我不应该使用totalrows而是fetch_array

3 个答案:

答案 0 :(得分:1)

因为将有1条记录,它永远不会超过1.

if ($totalRows_user > 1) 

应该是

if ($totalRows_user == 1) 

任何带有调试的东西,一旦工作就可以删除

$colname_user = 1; // debug

$db=new PDO("mysql:host=localhost;dbname=test;","root","");
$ami = $db->prepare('SELECT count(*),id FROM users WHERE id = :id');
$ami->bindParam(':id', $colname_user, PDO::PARAM_INT);
$ami->execute();

print_r($ami->errorInfo()); // debug

$totalRows_user = $ami->fetchColumn();
$result = $ami->fetch(PDO::FETCH_ASSOC);
while($row_user = $ami->fetch(PDO::FETCH_ASSOC)) {

    print_r($row_user); // debug

    }

<?php
if ($totalRows_user == 1) {
    ?>
 <a href="excluiru.php?id=<?php echo $row_user['id']; ?>">
<img src="imagens/delete.png" alt="Remover" onClick="return confirm('Do you really want to delete this User?');" /></a>Delete User
      <?php 
    } ?>

http://www.php.net/manual/en/pdo.prepared-statements.php

答案 1 :(得分:1)

if ($totalRows_user >= 1)

答案 2 :(得分:0)

@ emilio-gort和@amigura说得对,但是应该提到PHP 5.5(刚刚发布)弃用了MySQL扩展。您应该使用MySQLI或PDO,它们都提供适当的清理,这应该处理@ nick-r提到的Bobby表。