我的计划目标:
到目前为止我做了什么?
<?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初始化为ZERO。我怎么解决这个问题。如何在单击图像后保留增量值?
另外,我没有Javascript知识。所以,如果可能的话用php来解释我。
答案 0 :(得分:2)
你有不同的可能性来记住$ i。 e.g:
$_GET
:http://php.net/manual/en/reserved.variables.get.php
Cookie:http://php.net/manual/en/function.setcookie.php
会话:http://php.net/manual/en/features.sessions.php
也没有必要使用表格来解决这个问题。只需用超链接包装图像,然后通过递增参数来修改网址(index.php?i = 1,index.php?i = 2,index.php?i = 3等等。)
答案 1 :(得分: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>
答案 2 :(得分:0)
您可以使用会话,Cookie或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>