Cannot insert checkbox value into database - php

Hello i'm a newbie in PHP language. So I hope u guys can be simple with me. I need to create like a attendance system for a meeting. Now I was stuck at one part. I need to add a staff from a department for every created meeting event. The staff name was already appear when I click from dropdown menu for every department that retrieve from database. Now I tried to select from the checkbox staff that I want to add with the meeting id. But nothing is happened when I click the submit button after checked the staff name. I want to add to a new table with the meeting id. display.php is code I create to appear the staffname and to check the checkbox and retrieve the record from user table . The checkbox.php is for insert the checked checkbox to a table meetingstaff. Please anyone help me..
Here I attached my PHP code
display.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<form action="display.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<?php do { ?>
<form action="checkbox.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<tr >
<td><div align="center"><input name="chkl[]" type="checkbox" id="checkbox[]" value="<? echo $row_Recordset4['staffname']; ?>"></td>
<td><div align="center"><?php echo $row_Recordset4['staffname']; ?></div></td>
<td><div align="center"><?php echo $row_Recordset4['staffno']; ?></div></td>
</div></td>
</tr>
<?php } while ($row_Recordset4 = mysql_fetch_assoc($Recordset4));?>
checkbox.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<?php
$checkbox1 = $_POST['chkl'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox1);$i++) {
$query="INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')";
mysql_query($query) or die (mysql_error());
}
echo "Record is inserted";
}
?>

You need to INSERT a second parameter, or remove , staffno from the first part of the INSERT statement. You are passing just one value, but instructing for two columns.
So change your:
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')
to either
INSERT INTO meetingstaff (staffname) VALUES ('".$checkbox1[$i]."')
or perhaps
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."', ".$i.")

Related

can't delete from specific row from generate table from mySQL

Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?
Thank you!
<?php
$result= mysql_query("SELECT * from Staff ORDER BY status");
$count=1;
while($row=mysql_fetch_array($result)){
?>
<tr>
<td align="left"><?php echo $count; ?></td>
<td align="left"><?php echo $row['staffId']; ?></td>
<td align="left"><?php echo $row['name']; ?></td>
<td align="left"><?php echo $row['address'];?></td>
<td align="left"><?php echo $row['pNum'];?></td>
<td align="left"><?php echo $row['status'];?></td>
<td align="left"><?php echo $row['type'];?></td>
<td><input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
<input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">
</td>
</tr>
</tbody>
<?php
$count++; }
if(isset($_POST['deleteStaff'])){
$id=$_POST['staffId1'];
$result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
if($result){
echo '<script> location.replace("viewStaff.php"); </script>';
}
else{
?>
<script>
alert ("Fail to delete data")
window.location.href='viewStaff.php'
</script>
<?PHP
}
}
?>
I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.
Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.
example
<form action="deletion_script.php?staffid=<?php echo $staffid; ?>">
Put that inside of the td tag
Then in your deletion_script.php file, put something like this
<?php
//get staffid from URI
$staffid = $_GET['staffid'];
$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>
This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.
since the name for the hidden field is the same for all rows being generated the post request is pulling the value of the last row( also "staffId1" ).
I recommend either using a individual form for each row in which case your code doesn't change as much or use js to get the required staffID using selectors
If you include the same hidden field (StaffId1) for every record it will contain more then one value.
You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.
Button
type="submit" name="staffId" value="<?php echo $id ?>"
Php
$id=$_POST['staffId'];

How can i insert user id and status in mysql

My problem is only user id is inserted into database but I want to insert user id, date and radio button value. How can I insert radio button value into the database?
I have 3 employees and I want to insert user id, date and status of a particular user. I have a single submit button and if I press submit then I want to insert all data into database.
Here is my Code:
<form>
<input type="date" name="date" >
<table class="display data_tbl">
<thead>
<tr>
<th>
Date
</th>
<th>
Employee Name
</th>
<th>
Status
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
<?php
error_reporting(0);
$us=0;
$at="select * from user_information";
$atd=mysql_query($at);
while($data=mysql_fetch_array($atd))
{
$us++;
if(isset($_GET['submit']) && $_GET['submit']!='' && $_GET['date']!='')
{
$a=$_GET['date'];
echo $b=date('d-m-Y',strtotime($a));
$insert=mysql_query("insert into attendence set user_id='".$data['user_id']."',date='".$b."',status='".$_GET['radio']$us."'");
}
?>
<tr>
<td><?php echo $b;?></td>
<td align="center"> <?php echo $data['name'];?>
</td>
<td class="center">
</td>
<td class="center">
<input type="radio" name="radio<?php echo $us;?>" value="Late">Late
<input type="radio" name="radio<?php echo $us;?>" value="Absent">Absent
<input type="radio" name="radio<?php echo $us;?>" value="Present">Present
<input type="radio" name="radio<?php echo $us;?>" value="Halfday">Halfday
<input type="radio" name="radio<?php echo $us;?>" value="Leave">Leave
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<input type="submit" name="submit" value="Take Attendance">
</form>
firstly there is no need to give radio button name like you give because in radio button only one value can be selected at a time so remove the php value(i think you are using this to make radio button name unique) you are using with radio button name value from radio button name and than try.
You're insert statement has a syntax error, try replacing the following line
$insert=mysql_query("insert into attendence set user_id='".$data['user_id']."',date='".$b."',status='".$_GET['radio']$us."'");
with the following
$insert=mysql_query("insert into attendence(user_id, date, status) values('".$data['user_id']."','".$b."','".$_GET['radio'].$us."')");
There are many problem in your posted script
firstly as cyber_rookie mentioned, there is query syntax error in
data insert
secondly you have added submit button code inside while loop, which
is wrong, as while you are using for preparing display data and
submit code should be executed on submit button click
I have tried to make bit correct, please find code here https://jsfiddle.net/h5e5Lxnm/ you can check and modify it according to your requirement.
This code will give you all selected data (including date, radio vlaues and all)
EDIT:
My bad for saying you shouldn't use SET but here's another way for INSERT query:
INSERT INTO tablename (column1, column2, etc...) VALUES(value1, value2, etc....)
Applying to your code, this:
$insert=mysql_query("insert into attendence set user_id='".$data['user_id']."',date='".$b."',status='".$_GET['radio']$us."'");
to this:
$insert=mysql_query("insert into attendence (user_id, date, status)
values('".$data['user_id']."', '".$b."','".$_GET['radio'].$us."')");
And, your radio button should not have a different name so that the user can only select one option.

how to insert values from checkbox to MYSQL Database?

<table width="200" border="0">
<tr>
<td><p>
<?php while($row1 = mysql_fetch_array($res)){ ?>
<label>
<input type="checkbox" name="module" value="<?php echo $row1['MID']?>" id="<?php echo $row1['MID']?>">
<?php echo $row1['ModuleName']?></label>
<br>
<?php }?>
</p></td>
</tr>
</table>
I use this code to outout the checkboxes,and the checkboxes appear allright.
I m not sure about how,the data can be saved to the MYSL table.
the table i drew is in the form:
student_module{studentID,ModuleID}
what is the code i should write to enter the data to that table.
One student can enroll to many modules.
Using ajax functionality:
By clicking on checkbox collect the value of studentID and ModuleID and pass to the ajax method and then in your server end page, you can update db record.
Without ajax functionality
Post the form when user clicking on checkbox or put a save button below to submit the form on a PHP page and then you can collect all your values and update db accordingly.
<input type="checkbox" name="chk1[]" value="" ><?php echo $row1['ModuleName']?>
if(isset($_POST['submit']))
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
// now here in your insert query take mid='".$selected_checkbox."';
}

issue when inserting data in DB using submit button

i define below codes to show my products on website. I fetch my products details from Database.
When i click on the enquiry submit button it is not selecting the same id and inserting another product id in to database. Please see below codes which i use to send details in database using enquiry Submit Button
Please see below the updated codes, these are all codes which i am using to inserting data when clicking on enquiry submit button
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
</tr>
</table>
</td><br>
<?php
endwhile;
if($_REQUEST['enquiry'])
{
mysql_query("insert into orders values('$userid','$productid','$productprice')");
}
?>
Your table in your mysql database probably has the columns in a different order. To make sure, specify the columns in your insert query before specifying the values.
You're getting the wrong value for $productid because it's assigning the last value of it in your while loop, as your insertion code (and therefore your reference to it) is below that loop, you want to send the product id and price to the page accessible by $_REQUEST when the user clicks submit, to do this in your case you can use hidden form fields to store the values of each product, and a separate form for each element in your loop.
Also you want to put your submission code above your loop.
Depending where this data comes from you might want to escape it before inserting it in the database, I haven't in this example.
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
//check for submission and insert if set
if($_REQUEST['enquiry'])
{
//use the userid session for userid, and submitted values for productid and productprice
mysql_query("insert into orders values('$userid,'{$_REQUEST['productid']}','{$_REQUEST['productprice']}')");
}
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
//hidden form fields to store data to send to page
<input type="hidden" name="productid" value="<?php echo $productid;?>">
<input type="hidden" name="productprice" value="<?php echo $productprice;?>">
</tr>
</table>
</form>
<?php
endwhile;
?>

I cannot add data to my table in my mysql database

See php code below:
I have built the html form and the dropdown menu in the html form using <<<_END _END tags in php. also I added the following php code at the top of the htmlform that I had believed would allow me to enter a student name, student ID and select a course from the dropdown menu in the form. once those 3 values were entered in the form, the info should be added to the table enrolment in my mysql database. but i have had no luck figuring this out...
//connect3.php--login information to my mysql database//
<?php
define ('HOST', 'localhost');
define ('USER', 'root');
define ('PASS', '******');
?>
// html form and connection code//
<?php
include 'connect3.php';
$link = mysql_connect (HOST, USER, PASS) or die(mysql_error());
mysql_select_db ('milleruniversity', $link);
// Added mysql_real_escape() to protect against SQL-Injection
$code = mysql_real_escape( $_POST['code'] );
$uid = mysql_real_escape( $_POST['uid'] );
$studentname = mysql_real_escape( $_POST['studentname'] );
// Insert a row of information into the table "enrolment"
$query = "INSERT INTO enrolment (code, uid, studentname) VALUES('$code', '$uid', '$studentname')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
echo <<<_END
<table border='1'cellpadding="10">
<tr>
<td>
<h4>Miller University Registration Form</h4>
<p>Please Register as a new Student or current student for the following courses below.</p>
</td>
</tr>
<form action="draft5.php" method="post"><pre>
<tr>
<td>
Student Name <input type="text" name="studentname" maxlength="30"/>
</td>
</tr>
<tr>
<td>
Student ID <input type="text" name="uid" maxlength="11"/>
</tr>
</td>
<tr>
<td>
Select a course <select name="code" size="1">
<option value="DC-00040">Digital Communications</option>
<option value="VC-00030">Visual Culture</option>
<option value="WP-00080">World Politics</option>
</select>
</tr>
</td>
<tr>
<td>
<input type="submit" value="Submit to Register" />
</tr>
</td>
</pre></form>
</table>
_END;
mysql_close($link);
?>
It seems to me that you use this draft5.php page to display the form and to insert a row in your database. In that case the problem may come from the missing isset() around the $_POST data. (the first time you load the page the POST values are not set).
You could use this code :
if( (isset($_POST['code']) AND (isset($_POST['uid']) AND (isset($_POST['studentname']){
//process the data base treatment and display an acknoledgment of the insert
// Check if these new code, uid and studentname respect the primary key constraint
}
else{
// Display your form
}
You could also consider using backticks ` around the names of your tables and colomns.
If you want to prevent the same student to register twice in the same course you need to add primary keys in your tables. But this is not enough, indeed if you perform the insert request with a contraint violation on the primary key MySql will return an error. What you can do is check if the key exists prior to the insert request, if yes notify the user, if no perform the insert request.

Categories