Issue
this is my PHP script that lists all of my tags (from a MySQL database) with two radio buttons (enable and disable) for each row. how I can save the changes (if I enable or disable something) into the MySQL database? Whether I enable or disable a book it should save the value 1 or 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 />";
}
?>
Thanks. I hope you understand my question! :-)
Solution
I'll explain my code quoted in /* */
as I go further:
<?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>";
?>
Answered By - Grand Marshal Braev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.