PHP循环语法问题

时间:2011-10-25 15:43:18

标签: php

我需要在循环中添加一个计数器以及拉取内容。添加“和for($ ColCount = ColCount + 1)”

的语法是什么
<?php $ColCount = 0?>
<!--get artwork thumbnails --> 
<?php
$dbname = 'pdartist2';
$table = 'artwork';
// query
$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '$SCID' ") or die(mysql_error());
while($row = mysql_fetch_row($result))
{
    foreach($row as $cell)
    and for ($ColCount = ColCount + 1) 

echo "$ColCount", "$cell";
}
mysql_free_result($result);
?>

6 个答案:

答案 0 :(得分:2)

我不知道这在PHP中是否有效。也许它只是在$之前遗忘的ColCount符号。但你可以按照正常的方式去做:

foreach($row as $cell) {
    $ColCount++;

    echo $ColCount . $cell;
}

$ColCount = 0;

答案 1 :(得分:1)

代码:

<!--get artwork thumbnails -->      
<?php  
$dbname = 'pdartist2';  
$table = 'artwork';  
// query  
$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork   where SCID = '$SCID' ") or die(mysql_error());  
while($row = mysql_fetch_row($result))  
{  
    $colCount = 0;  
    foreach($row as $cell) {  
      $colCount++;  
      echo "$ColCount", "$cell";  
    }  
}  
 mysql_free_result($result);  

?>

答案 2 :(得分:0)

你错过了一个分号:

<?php $ColCount = 0?>

应该是:

<?php $ColCount = 0; ?>

while($row = mysql_fetch_row($result)) {
    foreach($row as $cell) {
        $ColCount++; // adds 1 to colcount

        echo $ColCount.$cell; // no need for quotes around variables. Also string concatination in PHP is using s dot (.)
    }
 }

mysql_free_result($result);

答案 3 :(得分:0)

正如布鲁斯所说,你可以做$ ColCount ++,但你也可以用mysql_num_rows计算结果

$result = mysql_query("SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '$SCID' ") or die(mysql_error());
$numRows = mysql_num_rows($result);

答案 4 :(得分:0)

我要做的就是使用像这样的数组

    <!--get artwork thumbnails --> 
    <?php
    $dbname = 'pdartist2';
    $table = 'artwork';

    # Define array
    $Count = array();

    // query
    $result = mysql_query('SELECT AID, ThumbFilePath, Title, DisplayOrder FROM artwork where SCID = '.$SCID) or die(mysql_error());
    while($row = mysql_fetch_row($result)){
        foreach($row as $cell){
            $Count[$Cell]['Count'] = $Count[$Cell]['Count']++;
        }

        echo $ColCount.', '.$cell;
    }
    mysql_free_result($result);

所以你有每个colomn的计数,但我建议使用mysql_num_rows();那样:

$ Query = mysql_query ... $ Count = mysql_num_rows($ Query);

$ Count将是一个数字;)

然后如果($ Count&gt; 0)

答案 5 :(得分:0)

如果您要计算每行中的列数,那么

while($row = mysql_fetch_row($result)) {
   $colCount += count($row);
}

虽然我没有看到这一点。 SQL结果集是一个完美的矩形数组。可变行数,但每行总是与结果集中的所有其他行具有相同数量的字段。您只需要计算ONCE列并缓存该值。