2012-09-20 33 views
-4

我的目标计划:在处理完动作后在php中增加变量?

  1. 在我的index.php文件,显示图像。
  2. 我想,当我用户点击该图像时,应该显示一个新的图像。
  3. 当他点击新图像时,应该会出现另一个新图像。

我到现在为止做了什么?

<?php 
$mycolor = array("red.jpg", "green.jpg", "blue.jpg"); 
$i = 0; 
$cc = $mycolor[$i++]; 
?> 


<form method="post" action="index2.php"> 
<input type="image" src="<?php echo $cc; ?>"> 
</form> 

我知道是什么错误。无论何时,页面被重新加载,变量$ i被初始化为零。如何解决这个问题。如何在点击图像后保留增加的值?

另外,我有没有使用Javascript知识。所以,如果可能的话解释我的php。

+0

你需要学习Javascript,因为你需要,可以用js来完成。 –

+0

我认为你需要学习JavaScript :-) – Miroslav

回答

0

您可以使用会议,饼干或POST变量来跟踪指数的,但有些你如何需要记住的最后一个索引,以便您可以+1按钮。以下是使用另一个(隐藏)帖子变量的示例:

<?php 

    // list of possible colors 
    $mycolor = array('red.jpg', 'green.jpg', 'blue.jpg'); 

    // if a previous index was supplied then use it and +1, otherwise 
    // start at 0. 
    $i = isset($_POST['i']) ? (int)$_POST['i'] + 1 : 0; 

    // reference the $mycolor using the index 
    // I used `% count($mycolor)` to avoid going beyond the array's 
    // capacity. 
    $cc = $mycolor[$i % count($mycolor)]; 
?> 

<form method="POST" action="<?=$_SERVER['PHP_SELF'];?>"> 

    <!-- Pass the current index back to the server on submit --> 
    <input type="hidden" name="id" value="<?=$i;?>" /> 

    <!-- display current image --> 
    <input type="button" src="<?=$cc;?>" /> 
</form> 
+0

我试过这种方法。但它没有奏效。可能,我们没有使用任何地方的身份证。 –

1
<?php 
$mycolor = array("red.jpg", "green.jpg", "blue.jpg"); 

if (isset($_POST['i'])) { // Check if the form has been posted 
    $i = (int)$_POST['i'] + 1; // if so add 1 to it - also (see (int)) protect against code injection 
} else { 
    $i = 0; // Otherwise set it to 0 
} 
$cc = $mycolor[$i]; // Self explanatory 
?> 


<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
<input type="image" src="<?php echo $cc; ?>"> 
<input type="hidden" name="i" value="<?php echo $i; ?>"> <!-- Here is where you set i for the post --> 
</form> 
+0

非常感谢。 –