PHP-如何在提交按钮单击时增加值
作者:互联网
我想知道每次发布元素时如何增加元素.
我必须使用for循环进行自动递增,但是我做错了.因此,任何建议或指导都会很棒.
这是我尝试做的方式:
谢谢
<?php
$id=0;
if (isset($_POST['submit'])) {
$do = $_POST['prodCode'];
$di = count($do);
while ($di > $id) {
$id++;
echo $id;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Session test</title>
</head>
<body>
<div class="holder">
<div class="im">
<img src="session-test/images/bestorange-juice.jpg" />
<p>bestorange-juice</p>
<form method="post" action="sessiontest.php">
<input type="hidden" id="prodCode" name="prodCode" value="f102" />
<input type="hidden" id="prodPrice" name="prodPrice" value="25" />
<!--<input type="text" id="prodQty" name="prodQty" value="1" size="1"/>-->
<input type="submit" value="send value" name="submit" id="submit" />
</form>
</div>
<div class="im">
<img src="session-test/images/milkshake-juice.jpg" />
<p>bestorange-juice</p>
<form method="post" action="sessiontest.php">
<input type="hidden" id="prodCode" name="prodCode" value="W122" />
<input type="hidden" id="prodPrice" name="prodPrice" value="1" />
<!--<input type="text" id="prodQty" name="prodQty" value="1" size="1"/>-->
<input type="submit" value="send value" name="submit" id="submit" />
</form>
</div>
</div>
</body>
</html>
解决方法:
尝试下面的代码,计数存储在会话中,但是对于现实生活中的应用,您应该使用数据库,并且还应该从数据库中获取产品:
<?php
// initialize counts for f102 and W122 products
if (!isset($_SESSION['count_f102']) {
$_SESSION['count_f102'] = 0;
}
if (!isset($_SESSION['count_W122']) {
$_SESSION['count_f102'] = 0;
}
if (isset($_POST['submit'])) {
$do = $_POST['prodCode'];
// increment count for product which was submitted
$_SESSION['count_'.$do] = 1+ (int) $_SESSION['count_'.$do];
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Session test</title>
</head>
<body>
<div class="holder">
<div class="im">
<img src="session-test/images/bestorange-juice.jpg" />
<p>bestorange-juice</p>
<form method="post" action="sessiontest.php">
<input type="hidden" id="prodCode" name="prodCode" value="f102" />
<input type="hidden" id="prodPrice" name="prodPrice" value="25" />
<input type="text" id="prodQty" name="prodQty" value="<?php $_SESSION['count_f102'] ?>" size="1" readonly="readonly" />
<input type="submit" value="send value" name="submit" id="submit" />
</form>
</div>
<div class="im">
<img src="session-test/images/milkshake-juice.jpg" />
<p>bestorange-juice</p>
<form method="post" action="sessiontest.php">
<input type="hidden" id="prodCode" name="prodCode" value="W122" />
<input type="hidden" id="prodPrice" name="prodPrice" value="1" />
<input type="text" id="prodQty" name="prodQty" value="<?php $_SESSION['count_W122'] ?>" size="1" readonly="readonly" />
<input type="submit" value="send value" name="submit" id="submit" />
</form>
</div>
</div>
</body>
</html>
标签:auto-increment,php 来源: https://codeday.me/bug/20191119/2037834.html