Am new to php... I have been battling on my dynamic checkboxes in such a way that if none is checked the form is return, also I need to retain what was checked when the form postback due to other invalid inputs.
$result = mysql_query("SELECT * FROM course") or die(mysql_error());
if ($result)
{
while ($row = mysql_fetch_array($result)){
if (isset($_POST['courses']) and $_POST['courses'] == $row['cid']) {echo $row['cid'];}
print "<input type=\"checkbox\" name=\"courses[]\" value=\"$row[cid]\">$row[cname]\n";
}
}
Help needed purely on php codes. Thanks in advance
Do this where the checkbox appears in the HTML on your php page:
<?php
$checked = isset($_POST["checkboxname"]) ? " checked" : '' ;
echo "<input type='checkbox' name='checkboxname' value='yes'" . $checked . ">";
?>
This will retain the checkbox state after the form has been posted.
UPDATE:
For your code, just do it like this, I think:
$result = mysql_query("SELECT * FROM course") or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_array($result)) {
$checked = '';
/* ERROR: if (isset($_POST['courses']) and $_POST['courses'] == $row['cid']) { */
if (isset($_POST['courses']) {
if (in_array($row['cid'], $_POST['courses']) {
echo $row['cid'];
$checked = " checked";
}
}
echo "<input type=\"checkbox\" name=\"courses[]\" value=\"$row[cid]\"" . $checked . ">$row['cname']\n";
}
}
EDIT: The condition needs to change too, I think, as I show in the code above.
Related
i want to check if a checkbox is checked through a mysql database request.
it should be something like this (just a concept code, what of course isnt working)
that should work probably with ajax, becouse i dont want to reload all the time:
$ergebnis = $mysqli->query("SELECT text,status FROM checkboxes where id=1 ;");
while($zeile = $ergebnis->fetch_array()) {
echo "<input type=\"checkbox\";
if ({$zeile['status']} == "true") {checked=\"checked\"}\n ;
echo " name=\"feld\" class=\"checkIt\"/>";
echo " {$zeile['text']}\n";
echo "";
}
?>
i have got 3 fields in the database. One text field where the text next to the checkbox shows up, a status field, where the script can see if something is "true" or "false" an a auto incrementation id.
I hope you can help me
write this code
$ergebnis = $mysqli->query("SELECT text,status FROM checkboxes where id=1 ;");
while($zeile = $ergebnis->fetch_array()) {
$text = "";
$text .= "<input type=\"checkbox\"";
if ({$zeile['status']} == "true") { $text .= " checked=\"checked\""; }
$text .= " name=\"feld\" class=\"checkIt\"/>";
$text .= "{$zeile['text']}";
echo $text;
//echo "";
}
There are so many errors was present in your code.
$ergebnis = $mysqli->query("SELECT text,status FROM checkboxes where id=1 ;");
while($zeile = $ergebnis->fetch_array()) {
echo '<input type="checkbox"';
if ({$zeile['status']} == "true") { echo ' checked="checked"'; }
echo ' name="feld" class="checkIt" />';
echo $zeile['text'];
}
?>
i try to make checkboxes. When i click checkbox it makes isPremium = 1 if i click a checked checkbox it makes isPremium = 0
However: when i click a checked checkbox it does not work..
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
$dbResult = mysql_query("select * from profiles");
while ($info = mysql_fetch_array($dbResult)) {
if ($info['isPremium'] == 0)
echo "<input type=checkbox name='check2[]' id='check2' value=" . $info['id'] . ">";
else
echo "<input type=checkbox name='check1[]' id='check1' value=" . $info['id'] . " checked>";
echo $info['profileName'] . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
if (isset($_POST['check2'])) {
$arrPremium = $_POST['check2'];
foreach ($arrPremium as $result) {
mysql_query("UPDATE profiles set isPremium=1 where id=" . $result . "");
}
}
else
{
$arrPremium = $_POST['check1'];
foreach ($arrPremium as $result2) {
mysql_query("UPDATE profiles set isPremium=0 where id=" . $result2 . "");
}
}
}
?>
when i click a checked checkbox it makes another checkbox unclick.
This is the checkbox page
I have refactored your code into this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$update = (isset($_POST['check']) && is_array($_POST['check']));
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
while ($info = mysql_fetch_array($dbResult))
{
if ($update)
{
$info['isPremium'] = (in_array($info['id'], $_POST['check']) ? 1 : 0);
mysql_query("UPDATE profiles SET isPremium = " . $info['isPremium'] . " WHERE id = " . $info['id']);
}
echo "<input type=checkbox name='check[]' value=" . $info['id'] . ($info['isPremium'] == 0 ? "" : "checked") . " />";
echo htmlspecialchars($info['profileName']) . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
?>
There were several problems with your original code:
Several HTML input elements with the same ID. This is wrong. We can have several elements with the same name attribute, but the id attribute should be unique for each element.
The database UPDATE code runs after displaying the form. This is wrong. In this case, we should update the database prior to generating the HTML output.
IMPORTANT: There is no need of two different POST arrays (check1 and check2). We only need one array. The checked boxes will be posted by the browser. The unchecked boxes will not be posted by the browser. As the id is the value, we can use the in_array function to verify if the checkbox for an item was checked or not.
It is a good idea to escape things you will output as HTML from the database. Otherwise, the application is vulnerable for some kinds of attack. The function htmlspecialchars is useful for this purpose.
If I understand correctly what you're trying to achieve, your code is needlessly complicated. You should use isset to check whether the value of a checkbox was included in the $_POST array. If yes, the checkbox was checked.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
echo "<form action='#' method='post'>";
$dbResult = mysql_query("SELECT * FROM profiles");
$profileid = array();
while ($info = mysql_fetch_array($dbResult)) {
echo "<input type=\"checkbox\" name=\"" . $info['id'] . "\" " . ($info['isPremium'] != 0 ? "checked " : "") . "/>";
echo $info['profileName'] . "<br />";
$profileid[] = $info['id'];
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
foreach ($profileid as $id) {
if (isset($_POST[$id])) {
mysql_query("UPDATE profiles SET isPremium=1 WHERE id=" . $id);
} else {
mysql_query("UPDATE profiles SET isPremium=0 WHERE id=" . $id);
}
}
}
?>
Checkboxes typically send the value "on" to the server, regardless of what value attribute is set. If you can, try to use radio buttons instead, as these send the proper value to the server. If that's not an option, have the name of the checkbox be check1[".$info['id']." and access array_keys($_POST['check1']).
<?php
$id = $_SESSION['user_id'] ;
echo "<form method='post' action='#'>";
echo "</select>
<p>Which Hospital Would You Like to Submit To?</p>";
$queryitem = "SELECT * FROM vendor_hospital WHERE vendor_hospital.user_id = '$id' AND vendor_hospital.approval_status = '1'" or die('MYSQL error: ' . mysql_error());
if ($result = mysql_query($queryitem)) {
if ($success = mysql_num_rows($result) > 0) {
echo "<select name='hospital_name'>";
echo "<option>-- Select A Facility --</option>";
while ($row = mysql_fetch_array($result))
echo "<option value='$row[manufacturer_id]'>$row[manufacturer_id]</option>";
echo "</select><br><br>";
} else {
echo "No results found.";
}
} else {
echo "Failed to connect to database.";
}
echo "<input type='submit' value='Submit' name='submit' class='button' /></form>";
?>
For some reason I'm stuck here. I'm just trying to get the manufacturer name to show in my options instead of the manufacturer_id. The manufacturer name is a foreign key in another table so I can't simply call $row[manufacturer_id] in my option tag. What should I do here? My only thought is to run a query inside the option tag for every manufacturer_id listed as a value but I'm sure that is overkill. Can someone point me in the right direction of a more elegant solution than that?
Not really sure what you are trying to do...but try this.
Replace this:
while ($row = mysql_fetch_array($result))
echo "<option value='$row[manufacturer_id]'>$row[manufacturer_id]</option>";
echo "</select><br><br>";
With this:
while ($row = mysql_fetch_array($result)){
echo "<option value='".$row['manufacturer_id']."'>".$row['manufacturer_id']."</option>";
}
echo "</select><br><br>";
Also be sure to double check and make sure that you are pulling from the right database, that it is populated, you are calling the right table names, etc...
I'm using a table to update a database, the table has 264 checkboxes which can be checked and unchecked then updated on the database.
I'm doing this by posting data on the form, using a while loop to set all fields to blank ( the value of the checkbox and the textarea value) for each respective field, then using a foreach loop to update each row in the database with the value of the checkbox.
Now, what I want to do is add the textarea value for each ticked checkbox into the database as well, what i cant figure out is how to do this?
This is my update code:
if (isset($_POST["update"])) {
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2)) {
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
$item = $_POST;
foreach($item as $key => $value) {
$wsID = str_replace("checkbox","",$key);
if (is_numeric($wsID)) {
$updateWSQ = "UPDATE seo_work SET taskValue=$value taskInfo=$value WHERE worksheetID=$wsID AND userID=$userID";
mysql_query($updateWSQ) or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
}
This is checkbox and textarea code: (please note this is within a form)
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id=checkbox'".$worksheetID."' checked='checked' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox".$worksheetID."' id='checkbox".$worksheetID."' />".
"<textarea class='textarea' name='textarea".$worksheetID."' id=textarea'".$worksheetID."'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
Use your HTML form like shown below.
$currentTask = '';
echo "<tr class='tr'>";
while ($seolistRow = mysql_fetch_array($seolistRes)) {
$taskValue = $seolistRow["taskValue"];
$worksheetID = $seolistRow["worksheetID"];
$taskName = $seolistRow["taskName"];
$taskInfo = $seolistRow["taskInfo"];
if ($taskValue == 1) {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' checked='checked' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
else {
$taskDone = "<input type='checkbox' value='1' class='checkbox' name='checkbox[".$worksheetID."]' id='checkbox[".$worksheetID."]' />".
"<textarea class='textarea' name='textarea[".$worksheetID."]' id='textarea[".$worksheetID."]'>" . $taskInfo . "</textarea>";
}
if ($currentTask != $taskName) {
echo "</tr>";
echo "<tr class='tr'>";
echo "<td class='task'>".$taskName."</td>";
}
echo "<td class='tick'>".$taskDone."</td>";
$currentTask = $taskName;
}
echo "</tr>";
See the modified name and id of your textarea and checkbox. I have modified it to textarea[SOME_WORKSHEET_ID] and checkbox[SOME_WORKSHEET_ID] respectively.
So, when you submit the form, you will receive those checkbox and textarea value as an array, with worksheetId as an index. You can use this [] technique to retrieve the values of the textarea and checkbox, or as many field you want to add in form.
Use above HTML structure and check the $_POST array.
Hope this will help..
Thanks!
Hussain.
You should be able to get the value in the textarea using $_POST['textarea' . $wsID] after your call to is_numeric.
Here is another approach, not completely tested, but hopefully you get the idea...
if (isset($_POST["update"]))
{
// All to blank
$seolistRes2 = mysql_query($seolistQ) or die(mysql_error());
while ($seolistRow2 = mysql_fetch_array($seolistRes2))
{
$wsID1 = $seolistRow2["worksheetID"];
$updateWSQ2 = "UPDATE seo_work SET taskValue=0, taskInfo='' WHERE worksheetID=$wsID1 AND userID=$userID";
mysql_query($updateWSQ2) or die(mysql_error());
}
// Re use your result from the select to go through all the known IDs
foreach($seolistRow2 as $i => $data)
{
// Obtain the ID
$id = $data['worksheetID'];
// Get the checkbox value for current ID
$checkbox_wsID = $_POST['checkbox' . $id];
// Get the textarea value for current ID
$textarea_wsID = $_POST['textarea' . $id];
// Update the Row using mysql_escape
$updateWSQ = "UPDATE seo_work " .
"SET taskValue = '" . mysql_escape_string($checkbox_wsID) ."' taskInfo = '" . mysql_escape_string($textarea_wsID) ."'" .
"WHERE worksheetID=$id AND userID=$userID";
mysql_query($updateWSQ)
or die(mysql_error());
header("Location: worksheet.php?y=".$seoworkyear."&userID=$userID&action=success");
}
}
What i'm trying to do is display a drop down with all field names from mysql database, once the user picks one and submits the form i want to display a second dropdown filled with all the rows from the submitted field name, this is my code so far:
$result = mysql_query("select * from `parts`") or die(mysql_error());
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
echo "<select name='field_names'>";
$i = 0;
while ($i < mysql_num_fields($result)) {
$fieldname = mysql_field_name($result, $i);
echo '<option value="'.$fieldname.'">'.$fieldname.'</option>';
$i++;
}
echo "</select>";
echo "<input type='submit' value='submit'></input>";
echo "</form>";
if($_POST) {
$fields = $_POST['field_names'];
$result1 = mysql_query("select '".$fields."' from `parts`") or die(mysql_error());
echo '<select name="fields">';
while ($row = mysql_fetch_array($result1)) {
echo "<option value=".$row[$fields].">".$row[$fields]."</option>";
}
echo '</select>';
}
Can anyone spot where i'm going wrong, thanks
there is a mistake on the line number 29
$result1 = mysql_query("select '" . $fields . "' from `parts`") or die(mysql_error());
you are using ' instead of `. Do as follows
$result1 = mysql_query("select `" . $fields . "` from `parts`") or die(mysql_error());
Hope your problem is solved.
As it stands now, the second set of selects will be issued OUTSIDE of your </form> tag, so will never get submitted with the rest of the form. At best, you should move the form closing tag to below the POST handler.
here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}
echo "</select>";
here username is the column of my table(userregistration)
it works perfectly