这是我的PHP脚本,列出了我的所有标签(来自MySQL数据库),每行有两个单选按钮(启用和禁用)。如何将更改(如果我启用或禁用某些内容)保存到MySQL数据库中?无论是启用还是禁用某本书,它都应保存值1或2.
<?php
$result = mysqli_query($mysqli,"SELECT * FROM tags ORDER BY id ASC");
while($row = mysqli_fetch_array($result)) {
if($row['enabled'] == 1) {
echo '<input type="radio" name="' . $row['id'] . '" value="1" checked>Enable' .
'<input type="radio" name="' . $row['id'] . '" value="2">Disable ';
} else {
echo '<input type="radio" name="' . $row['id'] . '" value="1">Enable' .
'<input type="radio" name="' . $row['id'] . '" value="2" checked>Disable ';
}
echo $row['tagname'] . "<br />";
}
?>
感谢。我希望你理解我的问题! : - )
答案 0 :(得分:1)
当我进一步说明时,我会解释/* */
中引用的代码:
<?php
/* ESTABLISH YOUR CONNECTION */
$mysqli=mysqli_connect("Host","Username","Password","Database"); /* JUST REPLACE THE NECESSARY HOST, USERNAME, PASSWORD AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if(isset($_POST['submit'])){ /* IF FORM HAS BEEN SUBMITTED */
/* STORE THE SUBMITTED POST DATA */
$counter=$_POST['hiddencounter'];
$radio=$_POST['radio'];
$id=$_POST['id'];
for($x=0;$x<=$counter;$x++){ /* FOR LOOP BASED ON THE HIDDEN COUNTER */
mysqli_query($mysqli,"UPDATE tags SET enabled='$radio[$x]' WHERE id='$id[$x]'"); /* UPDATE THE enabled COLUMN WITH THE CORRESPONDING SUBMITTED RADION BUTTON */
} /* END OF FOR LOOP */
} /* END OF ISSET */
$result = mysqli_query($mysqli,"SELECT * FROM tags ORDER BY id ASC");
echo "<form action='' method='POST'>"; /* SUBMIT ON PAGE ITSELF */
$counter=0; /* WILL SET AS YOUR COUNTER FOR ARRAY PURPOSES */
while($row = mysqli_fetch_array($result)) {
if($row['enabled'] == 1) {
echo "<input type='radio' name='radio[$counter]' value='1' checked> Enable <input type='radio' name='radio[$counter]' value='2'> Disable "; /* STORE THE RADIO BUTTON'S VALUE IN AN ARRAY */
}
else {
echo "<input type='radio' name='radio[$counter]' value='1'> Enable <input type='radio' name='radio[$counter]' value='2' checked> Disable "; /* STORE THE RADIO BUTTON'S VALUE IN AN ARRAY */
}
echo "<input type='hidden' name='id[$counter]' value='$row[id]'>"; /* STORE THE ID IN AN ARRAY */
$counter=$counter+1;
echo $row['tagname'] . "<br />";
} /* END OF WHILE LOOP */
echo "<input type='hidden' name='hiddencounter' value='$counter'>"; /* STORE THE TOTAL COUNT IN THE LOOP */
echo "<input type='submit' name='submit' value='Update'>";
echo "</form>";
?>
答案 1 :(得分:0)
你不应该保存radiobuttons,而是保存状态。如果可以启用或禁用状态(或:启用,是或否),则可以将其存储在名为'enabled'
的字段中,该字段为布尔类型,在MySQL中为BOOL
如果您希望保留其他状态的可能性,则可以将其存储在名为'state'
的字段中,该字段的类型为INT
或ENUM
。
BOOL:https://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html(它是TINYINT(1)的别名