I am trying to take input from an HTML form where there are checkboxes. The checkboxes are created with the student_ids from the database. Like so:
<td><input type="checkbox" name="{$row['STUDENT_ID']}" />
What I want to do is step through the Students table and check all of the entries against which of the checkboxes are checked. I want to then delete the entries from the database that have been checked with the checkboxes.
8 $query = "SELECT STUDENT_ID From Students";
9 $result = mysql_query($query) or die(mysql_error());
10 while($row=mysql_fetch_array($result)){
11 $checkname=$row['STUDENT_ID'];
12 foreach($_POST[$checkname] as $student_id =>val)
13 {
14 if($val == 'YES'
15 {
16 echo $_POST['STUDENT_ID'];
17 $query = "DELETE FROM Students WHERE STUDENT_ID" . mysql_real_escape_string($STUDENT_ID);
18 }
19 echo $query;
20 $result = mysql_query($query) or die(mysql_error());
21 //echo $POST['STUDENT_ID'];
22 }
23 }
Create an array of checkbox :
<input type="checkbox" name="studentID[]" value="{$row['STUDENT_ID']}" />
From PHP :
$studentID = $_POST['studentID'];
foreach($studentID as $ID){
echo $ID.'<br />'."\n";
}
EDIT :
Not sure but I think this is the right way :
$studentID = $_POST['studentID'];
$i=0;
foreach($studentID as $ID){
$i++;
echo $_POST['studentID'][$i].'<br />'."\n";
}
Try this for your form:
<input type="checkbox" name="STUDENT_ID[<?php echo $row['STUDENT_ID'] ?>]" value="YES" />
and this for your PHP loop:
foreach ($_POST['STUDENT_ID'] as $student_id => $val) {
if ($val == 'YES') {
$query = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
$result = mysql_query($query) or die(mysql_error());
}
}
A better way of doing this is to take the Student IDs from your checkboxes that were submitted and then run deletes on those.
HTML
<input type="checkbox" name="students_to_delete[]" value="{$row['STUDENT_ID']}" />
PHP
$students_to_delete = $_POST['students_to_delete'];
if(is_array($students_to_delete) && count($students_to_delete) > 0) {
$query = "DELETE FROM Students WHERE STUDENT_ID IN (" . implode(",", $students_to_delete) . ")";
$result = mysql_query($query) or die(mysql_error());
}
The above code is vulnerable to SQL injection. If someone posts back to the server a value of 0 OR STUDENT_ID!=0 then all rows in the Students table will be deleted.
Your code is also inefficient - you are returning all the students and then iterating over each student to see if this requires deleting.
You would be better using in your markup:
<input type="checkbox" name="STUDENT_TO_DELETE" value="$row['STUDENT_ID']" />
and then in the php:
foreach ($_POST['STUDENT_TO_DELETE'] as $student_id => $val) {
$sql = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
mysql_query($sql);
}
}
Related
i have multiple checkbox values in my form as shown in figure
I know i can store values for single checkbox in db but here situation is slightly different,so ho could i successfully store them in different different rows for same db.
my table struture is
1.content_table
title,description,category_id(fk),course_id(fk),subject_id(fk),content_type_id(fk)
2.category_table
entrance,school,ug,pg
3.subject_table
english,hindi,maths......
4.content_type_table
notes,summary,videos,question_bank
i have to insert data from shown form in content_table which store data by category_id,course_id,subject_id,content_type_id
i have tried following code which is only working for single checkbox i.e category ,so please someone suggest me how to do for different type of checkbox.
my code is
<?php
include 'includes/dbconfig.php';
if($_SERVER['REQUEST_METHOD']=='GET')
{
echo $title = $_GET['title'];
echo $description = $_GET['description'];
echo $content_url = $_GET['content_url'];
echo $thumb_icon_url = $_GET['thumb_icon_url'];
$category = $_GET['category'];
$course = $_GET['course'];
echo $select_subject = $_GET['select_subject'];
echo $select_content_type = $_GET['select_content_type'];
foreach (array_combine($category, $course) as $cat => $cose) {
$sql = mysqli_query($conn,"SELECT category_id from category_ref_table where category = '$cat'") or die(mysqli_error());
$row = mysqli_fetch_array($sql,MYSQLI_ASSOC);
echo $category_id = $row['category_id'];
$sql1 = mysqli_query($conn,"SELECT course_id from course_ref_table where course = '$cose'") or die(mysqli_error());
$row1 = mysqli_fetch_array($sql1,MYSQLI_ASSOC);
echo $course_id = $row1['course_id'];
$sql2 = mysqli_query($conn,"SELECT subject_id from subject_ref_table where subject = '$select_subject'") or die(mysqli_error());
$row2 = mysqli_fetch_array($sql2,MYSQLI_ASSOC);
echo $subject_id = $row2['subject_id'];
$sql3 = mysqli_query($conn,"SELECT content_type_id from content_type_table where content_type = '$select_content_type'") or die(mysqli_error());
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
echo $content_type_id = $row3['content_type_id'];
mysqli_query($conn,"INSERT INTO content_ref_table (title,description,content_url,thumb_icon_url,category_id,course_id,subject_id,content_type_id,login_id)VALUES ('$title','$description','$content_url','$thumb_icon_url','$category_id','$course_id','$subject_id','content_type_id')");
}
}
?>
try something like this(array variable)
<input type="checkbox" name="category[]" value="entrance">
<input type="checkbox" name="category[]" value="School">
<input type="checkbox" name="category[]" value="ug">
<input type="checkbox" name="category[]" value="pg">
Upon using like this you can get the list of checked items as an array. After that do the required save it in your table.
Suppose someone selects 2 students along with 1 teacher
How do I send/create 2 different records in MYSQL database,
- one NEW Record for each student/teacher combo
HTML:
1.) Here I can Select as many as "FOUR" students:
<input type="checkbox" name="ALM[]" value="Bob" >Bob<br />
<input type="checkbox" name="ALM[]" value="Stacy" >Stacy<br />
<input type="checkbox" name="ALM[]" value="John" >John<br />
<input type="checkbox" name="ALM[]" value="Liam" >Liam<br />
2.) Here below I am Selecting "ONE" Teacher:
<select name="TCH">
<option value="Dan">Dan</option>
<option vaule="Rick">Rick</option>
If I select Bob and Stacy (students) and Rick (teacher) I need.
2 records 1.) Bob | Rick. 2.) Stacy | Rick.
PHP:
This is my PHP where I Separate the incoming Checkbox Data and try to send to Database
$ALM = implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$query = "INSERT INTO cl_st_tch (students_id,teachers_id)
VALUES"; for ($i=0; $i<sizeof($ALM); $i++)
$query .= "('" . $ALM[$i] . "','$TCH'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );
What am I missing? Any Help would be greatly appreciated
To avoid multiple SQL queries a single query can be built.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$arr = array();
$query = 'INSERT INTO cl_st_tch (students_id,teachers_id) VALUES ';
foreach($ALM as $student){
$arr[] = '('.$student.','.$TCH.')';
}
if(!empty($arr)) {
$query .= implode(', ', $arr);
mysql_query($query);
}
?>
Since your ratio is 1:n (1 teacher to many students),
Iterate through each of the students and add a teacher to each one.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
foreach($ALM as $student){
$query = "INSERT INTO cl_st_tch (students_id,teachers_id) VALUES($student, $TCH)";
mysql_query($query);
}
?>
I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form :
$n = array(); //Supplier Name
$s = array(); //Short Name
$o = array(); //Shipment No.
$id = array(); //Supplier ID
<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required name="o[]">
<input type="submit" value="Confirm Editing" >
</form>
Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow :
if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){
//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){
//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//End of for Each id
}
}
What actually Does, When Selecting a single row to update..It works perfectly ! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. to all the selected rows.
I think this is due to the series of foreach within the foreach($id). I would write :
foreach($_POST['id'] as $index=>$id) {
to keep track of the index of your record, and then do not do any other foreach but rather :
$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";
so you keep the link between the $id value and the other variables.
I have 2 tables relating to a survey. When user answers each set of questions and then click the submit button, it will loop each answer according to the form submitted in order to check within the database first, if the CustomerID and QuestionID have been found, then do the Update. If not found, do the Insert instead.
QUESTIONS table
QuestionID (PK)
QuestionText
ANSWERS table
AnswerID (PK)
CustomerID (FK)
QuestionID (FK)
AnswerText
<html>
....
<form action="/db.php" method="POST">
<?php echo $questiontext[1]; ?><input type="text" name="answer1" id="answer1">
<?php echo $questiontext[2]; ?><input type="text" name="answer2" id="answer2">
<?php echo $questiontext[3]; ?><input type="text" name="answer3" id="answer3">
<?php echo $questiontext[4]; ?><input type="text" name="answer4" id="answer4">
<?php echo $questiontext[5]; ?><input type="text" name="answer5" id="answer5">
<?php echo $questiontext[6]; ?><input type="text" name="answer6" id="answer6">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
...
</html>
db.php
<?php
if(isset($_POST['submit'])) {
$cusid = intval($_POST['CustomerID']);
$answer1 = $db->real_escape_string($_POST['answer1']);
$answer2 = $db->real_escape_string($_POST['answer2']);
$answer3 = $db->real_escape_string($_POST['answer3']);
$answer4 = $db->real_escape_string($_POST['answer4']);
$answer5 = $db->real_escape_string($_POST['answer5']);
$answer6 = $db->real_escape_string($_POST['answer6']);
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$quesid."','".$answer."')";
$res = $db->query($sql) or die ('Error: ' . mysqli_error($db));
}
?>
My questions are:
How to update each answer(1-6) one by one and then insert into the database if CustomerID and QuestionID have not been found by using array and SQL query, if found, then just update?
How could I reference the QuestionID in order to related with AnswerText in HTML and PHP?
This is just an idea for you. Hope you can understand it. Make sure you replace database driven functions with your $db object.
if(isset($_POST['submit'])) {
$sql = "SELECT QuestionID FROM Questions ORDER BY QuestionID ";
$res = $db->query($sql);
$qus = 1;
while ($row = mysqli_fetch_array($res , MYSQLI_ASSOC)) {
{
$questionID = $row['QuestionID'] ;
$answer = $db->real_escape_string($_POST['answer' . $qus ]);
$sql = "SELECT AnswerID FROM Answers WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
$resAns = $db->query($sql);
$num_rows = $resAns->num_rows; // This should be replace with your $db object record count obtaining method
if($num_rows == 1)
{
$sql = "UPDATE Answers SET AnswerText = '$answer' WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
// Execute your update query
}
else
{
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$questionID."','".$answer."')";
// Execute your insert statement
}
$qus ++;
}
}
You can run a select query first and then see how many rows have been returned from there something like this
$check = mysql_query("SELECT * FROM Answers WHERE CustomerId = '$cusid' OR QuestionId = '$quesid' LIMIT 1") or die(mysql_error());
$num_rows = mysql_num_rows($check);
if($num_rows == 1)
{
// value exists run the update
}
else
{
// go ahead with insert query
}
If you set a unique key on CustomerID+QuestionID, then you can just do an INSERT ... ON DUPLICATE KEY UPDATE ...
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Let the database handle the checks.
I am trying to display some rows from a database table based on choices submitted by the user. Here is my form code
<form action="choice.php" method="POST" >
<input type="checkbox" name="variable[]" value="Apple">Apple
<input type="checkbox" name="variable[]" value="Banana">Banana
<input type="checkbox" name="variable[]" value="Orange">Orange
<input type="checkbox" name="variable[]" value="Melon">Melon
<input type="checkbox" name="variable[]" value="Blackberry">Blackberry
From what I understand I am placing the values of these into an array called variable.
Two of my columns are called receipe name and ingredients(each field under ingredients can store a number of fruits). What I would like to do is, if a number of checkboxes are selected then the receipe name/s is displayed.
Here is my php code.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("****") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
echo "$variablename is checked";
}
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
foreach ($_POST['variabble'] as $ingredients)
echo $row[$ingredients] . '<br/>';
?>
I am very new to php and just wish to display the data, I do not need to perform any actions on it. I have tried many select statements but I cannot get any results to display. My db connection is fine and it does print out what variables are checked.
Many thanks in advance.
EDIT:
Thanks a million for replying. However, I tried correcting my own code=blank page and both solutions above ==blank pages also. Grrrr!! Here is one solution I tried.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
I also tried
<?php
// Make a MySQL Connection
mysql_connect("localhost", "24056", "project99") or die(mysql_error());
mysql_select_db("24056db2") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM horse WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
?>
I suppose another way to say it, if the checkbox variable is equal to a record under the ingredients column, I wish to print out the receipename of that record.
Im nearly getting confused here mysellf, haha.
Any other ideas I could try???
Correction in ur code
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
Do u see the difference above?
Place "$query" in place of "$result" mysql_fetch_assoc($result)
My Solution
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM fruit WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
Your question is not clear to me, you may try the following-
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
NOTE: This code is not tested