我正在while循环中查询表,并且有一个按钮可以在单击时更新每一行的数据。但是更新没有发生。
在单击该行的提交按钮后,将更新表列“注册”。
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('mydata');
$query = "SELECT * FROM internship";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['Enroll']=="unenroll")
{
echo '<div class="intern">';
echo '<h1>'.$row['course'] . "</h1>" ;
echo '<h2>'.$row['compay'] . "</h2>";
echo "<h3>Stipend:Rs." . $row['stipend'] ."<h3>";
echo "<h3>Duration:".$row['duration']."month</h3>";
echo "<h3>Start-date:".$row['start date']."</h3>";
echo '</div>';
echo '<form method="post" action="">';
echo '<button name="add_to_cart" type="submit" ><h2>Enroll</h2></button>';
echo '</form>';
if(isset($_POST["add_to_cart"]))
{
$selectedProduct = $row["ID"];
$sql='UPDATE internship SET Enroll="enrolled" WHERE ID="$selectedProduct"';
mysql_query($connection,$sql);
header("location:enrolled.php");
}
}
}
mysql_close($connection);
?>
我无法更新。请帮忙。
答案 0 :(得分:1)
您的代码几乎没有问题,例如:
您没有在每一行的按钮中包含任何 ID 值。
echo '<button name="add_to_cart" type="submit" ><h2>Enroll</h2></button>';
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> no value="..."
您没有使用所选的行,即单击了按钮的行以使用 enrolled 更新表行。
$selectedProduct = $row["ID"];
^^^^^^^^^^
所以您的代码应如下所示:
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('mydata');
if(isset($_POST["add_to_cart"])){
$selectedProduct = $_POST['add_to_cart'];
$sql ="UPDATE internship SET Enroll = 'enrolled' WHERE ID = '$selectedProduct'";
mysql_query($connection,$sql);
header("location:enrolled.php");
exit();
}
$query = "SELECT * FROM internship";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['Enroll']=="unenroll"){
?>
<div class="intern">
<h1><?php echo $row['course']; ?></h1>
<h2><?php echo $row['compay']; ?></h2>
<h3>Stipend:Rs <?php echo $row['stipend']; ?><h3>
<h3>Duration: <?php echo $row['duration']; ?> month</h3>
<h3>Start-date: <?php echo $row['start date']; ?></h3>
</div>
<form method="post" action="">
<button name="add_to_cart" value="<?php echo $row['ID']; ?>" type="submit"><h2>Enroll</h2></button>
</form>
<?php
}
}
mysql_close($connection);
?>
边注::请勿使用mysql_*
函数,从PHP 5.5开始不推荐使用这些函数,并且在PHP 7.0中将其完全删除。请改用mysqli
或pdo
。 And this is why you shouldn't use mysql_*
functions。