自动递增变量

时间:2014-12-23 14:08:35

标签: php variables

我试图通过从数据库中提取的每个步骤来增加步骤编号。这是我的代码:

//get the project steps 
$ID=mysqli_real_escape_string($con,$_GET['id']);         
      $projSteps="SELECT project_steps.projectStepDesc,project_steps.projectID FROM project_steps WHERE project_steps.projectID=$ID";  
    $results1 = mysqli_query($con,$projSteps);  
    if (!$results1) {
printf("Error: %s\n", mysqli_error($con));
exit();
}   
       if (mysqli_num_rows($results1) > 0){
        echo '<h2>Project Steps:</h2>';           

 while ($rows = mysqli_fetch_assoc($results1))
    {
      $a=1;
      echo "Step ". $a++ ."<br />";
      $psteps=$rows['projectStepDesc'];
      echo '<div id="steps">';
      echo "$psteps";
      echo '</div>';
      }}//end project steps

这只是在每一步输出步骤1。我试图说出第1步,第2步,第3步等。我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

您在while循环中声明计数器。这不会起作用,每次循环执行时都会调用$a = 1;。变化:

while ($rows = mysqli_fetch_assoc($results1))
    {
      $a=1;

要:

$a=1;
while ($rows = mysqli_fetch_assoc($results1))
    {

答案 1 :(得分:2)

您每次都在循环中设置$a = 1。把它放在循环外面。

答案 2 :(得分:0)

你已经把$ a = 1置于其他时间,另一方面,当循环运行时,a的值每次变为1。

    $ID=mysqli_real_escape_string($con,$_GET['id']);         
  $projSteps="SELECT project_steps.projectStepDesc,project_steps.projectID FROM         project_steps WHERE project_steps.projectID=$ID";  
$results1 = mysqli_query($con,$projSteps);  
if (!$results1) {
      printf("Error: %s\n", mysqli_error($con));
     exit();
   }   
   if (mysqli_num_rows($results1) > 0){
    echo '<h2>Project Steps:</h2>';           
     $a=1;
       while ($rows = mysqli_fetch_assoc($results1))
    {

  echo "Step ". $a++ ."<br />";
  $psteps=$rows['projectStepDesc'];
  echo '<div id="steps">';
  echo "$psteps";
  echo '</div>';
  }}//end project steps