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.
Related
I'm developing a simple student information system, for now i have 300 students and six subjects, so when i want to add marks obtained by each student i use html form and php script to add those marks, for each student i add marks for six subjects that is one subject at a time, so i'm asking if there is the way where by php can allow me retrieve one student and add all the marks for the six subjects at once and then take another and so on. Also i want to calculate total marks for each student and store those total in another table with respective student id so that i can know who is the first student and who is the last by using that total marks of each student.
here is the way i'm doing right now
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<html>
<body>
<div>
<div>
<form action="connmarks.php" method="post">
<table>
<tr><td colspan="6"> </td></tr>
<tr><td><p>Adding Student Results</p></td></tr>
<tr>
<td width="9%">Student Code<?php echo $mstudentcode;?></td>
<td width="17%"><input name="student_code" type="text" size="30" value="<?php echo $studentcode;?>" /></td></tr>
<tr>
<td width="10%">Subject Code<?php echo $msubjectcode;?></td>
<td width="18%"><input name="subject_code" type="text" size="30" value="<?php echo $subject_code;?>"/></td></tr>
<tr>
<td width="12%">Marks<?php echo $mmark;?></td>
<td width="34%"><input name="mark" type="text" size="30" value="<?php echo $mark;?>"/></td>
</tr>
<td> </td>
<td>
</td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr><td colspan="6"> </td></tr>
<tr>
<td> </td><td colspan="6"><input type="submit" name="save" value="Add Marks" /></td>
</tr>
<tr><td colspan="6"><?php echo $sms1.$sms.$sms2;?></td></tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?></div>
</div>
</body>
</html>
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<?php
session_start();
if(isset($_POST['save']))
{
// validating student code
if(empty($_POST['student_code']))
{
$mstudentcode='<font color="red"><b>**</b></font>';
}
else
{
$student_code=$_POST['student_code'];
}
// validation for kiswahili subject
if(empty($_POST['subject_code']))
{
$msubjectcode='<font color="red"><b>**</b></font>';
}
else
{
$subject_code=$_POST['subject_code'];
}
// validating english subject
if(empty($_POST['mark']))
{
$mmark='<font color="red"><b>**</b></font>';
}
else
{
$mark=$_POST['mark'];
}
// checking if there is any error message, if no error proceed, if there is error, display the error
// Then exit the script and redirect at the same page
if($mstudentcode||$msubjectcode||$mmark||$sms)
{
$sms1='<font color="red"><b>Error found,please check **</b></font><br/>';
include 'addmarks.php';
exit;
}
// if there is no error include connection file
if($student_code&&$subject_code&&$mark)
{
// include 'mysqli_connect.php';
require_once ('../../mysqli_connect.php');
$addmarks= "insert into result(student_code,subject_code,mark) values ('".$student_code."','".$subject_code."','".$mark."')";
$k = mysqli_query($dbc, $addmarks);
if ($k)
{
$sms1='<font color="green"><b>Student Marks Submitted Successfully</b></font><br/>';
include 'addmarks.php';
exit;
}
else
{
$sms1='<font color="red"><b>Failed To Add Student Marks</b></font><br/>';
include 'addmarks.php';
exit;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<!-- Displays all users in database in a select option -->
<select name="students">
<option>Student 1</option>
<option>Student 2</option>
<?php
//This code below is what you will need to use for yours to pull values out of the database(changing the values to suit yours obviously).
// $query = "SELECT * FROM students ORDER BY student_name ASC";
// $result = mysqli_query($conn,"$query");
// while($row = mysqli_fetch_assoc($result)){
// echo "<option>" . $row['student_name'] . "<br></option>";
// }
?>
</select><br>
<!-- All the different input fields for maths, english and science -->
<input type="text" name="eng_grade" value="" placeholder="Enter English Grade"><br>
<input type="text" name="math_grade" value="" placeholder="Enter Maths Grade"><br>
<input type="text" name="science_grade" value="" placeholder="Enter Science Grade"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//If submit is pressed
if (isset($_POST['submit'])) {
//this gets the value of the student name from the select box and stores it as $student
$student = $_POST['students'];
//These gets the values stored in the inputs above and store them in the 3 vairables
$english = $_POST['eng_grade'];
$maths = $_POST['math_grade'];
$science = $_POST['science_grade'];
//this is a mysql query that updates the data with whatever you put into the database(to add to existing tables you will have to dig abit deeper and create your
//database with all the correct fields!
$query = "UPDATE students SET maths_grade = '$maths', $english_grade = '$english', science_grade = '$science' WHERE student_name = '$student'";
$update = mysqli_query($conn, "$query"); //<-- this inserts the values into the database, changing the current #null value (null means nothing is in it)
}
?>
</body>
</html>
Create 2 tables, one for student and other for marks.
In one table, just insert student name and id(unique), and in other table student all 6 subject marks i.e. 6 columns for 6 sub, 1 for student id, and other one as auto increment id column.
So using that student id you can retrieve all the subject marks of a particular student.
Edit: Just noticed this question is 3 years old w00t!?
Drafting tables would be something like
student table:
id primarykey integer
name notnullable nvarchar(255)
subject table
id primarykey integer
name notnullable nvarchar(255)
student_subject table
id primarykey integer
student_id foreignkey notnullable unique integer
subject_id foreignkey notnullable unique integer
mark notnullable double(2,2)
E.g. Select the marks of a subject
Select student.name, subject.name, subject_student.mark from subject_student
inner join student on student.id = subject_student.student_id
inner join subjecton subject.id = subject_student.subject_id
where student_id = X; // X is the id of the student you want
Any calculation should be based on query, you don't want to store results in the database. You want data in the database and since it's volatil data (can be changed anytime), it's easier and faster to calculate whenever required. Sum, GroupBy, there are a ton of basic sql keywords that can help you. student_subject table is the table where it combines that Many students in Many subjects with a certain mark. If you want to save a student's mark, you just Insert into this table the id's and the mark value.
Since it's a school project, this should be suffice for you to work it out.
In the future, take a look at prepared statements
http://php.net/manual/en/book.pdo.php
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.
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.")
I seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.
I'm not in a very good level in php coding. i have a php interface(code: insert.php) which has four forms that are used to enter data to four different tables in my database and data entry to the forms are independent from each other. but, when i enter data to a form, it results in "undefined index error" pointing two variables which are related to another form in the interface. and also, data is not entered to the table in the database. not all the forms cause this error.they work fine.
this is the code of 'insert.php' the form i need data to be inserted.
<form method="post" action="input.php">
<tr>
<td>ID</td>
<td><input type="text" name="cat_id" size="40">
</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea NAME="desc" COLS=31 ROWS=6></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'insert.php', the error variables related to.
<form method="post" action="input.php">
<tr>
<td>ItemID</td>
<td><input type="text" name="item_id" size="40">
</td>
</tr>
<tr>
<td>EPF</td>
<td><input type="text" name="epf" size="40">
</td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="quan" size="40">
</td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="date" size="40">
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<input type="submit" name="submit" value="Done">
</td>
</tr>
this is the code in 'input.php'.
<?php
$cat_id=$_POST['cat_id'];
$cat_descr=$_POST['desc'];
$query_cat = "INSERT INTO 'category' ( id, description)
VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
$result_cat = mysql_query($query_cat);
?>
<?php
$item_id=$_POST['item_id'];
$epf2=$_POST['epf'];
$quan=$_POST['quan'];
$date=$_POST['date'];
$query_itemEmp = "INSERT INTO 'emp_div_item' ( epf, item ,quantity, date)
VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
$result_itemEmp = mysql_query($query_itemEmp);
?>
<?php
if( $result_emp || $result_cat || $result_item || $result_itemEmp){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
?>
the variables which the error points out are $quan and $date.. $result_item and $result_emp are query results get from other forms which work fine.please note that users dont need to enter data to all forms at a time. they can chose whatever the number of forms to be filled at a time.
plese help me to solve this problem and thank you in advance.
I think the problem is with the HTML code, you are having two seperate forms :
<form method="post" action="input.php"> ---first one
<form method="post" action="input.php"> --- second one
So when you click on first form's submit, only that form's data will be submitted (here , only cat_id and desc will be available in input.php)
And then you try access other forms values in the same input.php ($item_id=$_POST['item_id']; which is not present with the first form's data.
Hence you get this error.
Also if you will try to submit the second form, the you will get the same error for $cat_id and $cat_descr variables.
So keep all the data in a single form.
As far as your queries concerned: don't put quotes around db identifiers. Use ticks if you need to.
That being said change
$query_cat = "INSERT INTO 'category' (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
^ ^
to
$query_cat = "INSERT INTO category (id, description) VALUES ('$cat_id','$cat_descr')" or die (mysql_error());
and
$query_itemEmp = "INSERT INTO 'emp_div_item' (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
^ ^
to
$query_itemEmp = "INSERT INTO emp_div_item (epf, item ,quantity, date) VALUES ('$epf2','$item_id','$quan','$date')" or die (mysql_error());
On a side note: your code in current state vulnerable to sql-injections. Learn and use prepared statements with either mysqli or PDO. mysql_* extension is deprecated and is no longer supported.