So I'm producing this booking system for supplementary lessons in school,and I'm new to coding.So I'm experiencing many problems when making this.
I'm using PHP and mysql for my system.The following is my tedious 100-line-code for 'sinsert.php'
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Booking Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Prevent empty fields
$date = $room = $tid = $subj = $start = $end = $noofstu = null;
$nodate = $noroom = $notid = $nosubj = $nostart = $noend = $nonoofstu = null;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$nodate = "*Date of lesson is required";
$date = null;
} else {
$date = $_POST["date"];
}
if (empty($_POST["room"])) {
$noroom = "*Room is required";
$room = null;
} else {
$room = $_POST["room"];}
if (empty($_POST["tid"])) {
$notid = "*Teacher in charge is required";
$tid = null;
} else {
$tid = $_POST["tid"];}
if (empty($_POST["noofstu"])) {
$nonoofstu = "*Number of Students Attending is required";
$noofstu = null;
} else {
$noofstu = $_POST["noofstu"];}
}
function ($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
?>
<div id='frm'><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<p><h1><u>Lesson Booking Form</u></h1></p>
<p>
<label>Date of Lesson:</label>
<input type="date" name="date" >
<br><span class="error"><?php echo $nodate;?></span>
</p>
<p>
<label>Room:</label><br>
<input type="radio" name="room" value="246"/> Room 246
<input type="radio" name="room" value="340"/> Room 340
<input type="radio" name="room" value="342"/> Room 342<br>
<span class="error"> <?php echo $noroom;?></span>
</p>
<p>
<label>Teacher in charge:</label><br>
<input type="radio" name="tid" value="T001"/>Mr.Williams
<input type="radio" name="tid" value="T002"/>Mr.Zimmerman
<input type="radio" name="tid" value="T003"/>Ms.Alcott<br>
<span class="error"> <?php echo $notid;?></span>
</p>
<p>
<label>Subject:</label>
<select name="subj">
<option value="unitA">Unit A</option>
<option value="unitB">Unit B</option>
<option value="unitC">Unit C</option>
<option value="unitD">Unit D</option>
<option value="unitE">Unit E</option>
<option value="unitF">Unit F</option>
</select>
</p>
<p>
<label>Starting Time:</label>
<select name="start">
<option value='09:00:00'>09:00</option>
<option value='10:00:00'>10:00</option>
<option value='11:00:00'>11:00</option>
<option value='12:00:00'>12:00</option>
<option value='13:00:00'>13:00</option>
<option value='14:00:00'>14:00</option>
<option value='15:00:00'>15:00</option>
<option value='16:00:00'>16:00</option>
<option value='17:00:00'>17:00</option>
</select>
<label>Ending Time:</label>
<select name="end">
<option value='10:00:00'>10:00</option>
<option value='11:00:00'>11:00</option>
<option value='12:00:00'>12:00</option>
<option value='13:00:00'>13:00</option>
<option value='14:00:00'>14:00</option>
<option value='15:00:00'>15:00</option>
<option value='16:00:00'>16:00</option>
<option value='17:00:00'>17:00</option>
<option value='18:00:00'>18:00</option>
</select>
</p>
<p>
<label>Number of Students Attending:</label>
<input type='number' name='noofstu' min='1'max='40'><br>
<span class="error"><?php echo $nonoofstu;?></span>
</p>
<p>
<input type="reset" id="reset" value="Reset">
<input type="submit" id="submit" value="Submit">
</p>
</form>
<?php
//Insert data in mysql database
$date = $_POST['date'];
$room = $_POST['room'];
$tid = $_POST['tid'];
$subj = $_POST['subj'];
$start = $_POST['start'];
$end = $_POST['end'];
$noofstu = $_POST['noofstu'];
$conn = #mysqli_connect("localhost","root","","sba");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "INSERT INTO booking (date, room, tid, subj, start, end, noofstu) Values (?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param( $_POST['date'], $_POST['room'], $_POST['tid'], $_POST['subj'], $_POST['start'], $_POST['end'], $_POST['noofstu']);
$stmt->execute();
if(!mysqli_query($conn, $sql))
{
echo "Not Inserted!";
}
else
{
echo "Inserted";
}
$conn->close();
?>
</div>
</body>
There are two codes in 'sinsert.php'.The first code is to make sure the user filled in all fields before submitting or else error codes will appear.The first code is mostly copied from W3schools.So I don't think there will be any problems regarding this code.
The second code is to insert the inputted data into the 'booking' table in the 'sba' database.I made code with the help of my teacher's code and PHP: Inserting Values from the Form into MySQL
The 'booking' table consists of 8 fields.Besides the 7 fields mentioned in the code,there's also primary key field 'bookid' which is in auto increment
Here are the problems I encountered
1.Everytime I went to the 'sinsert.php' page,I got 2 warning messages beneath my form
The first warning message states: 'mysqli_prepare() expects exactly 2 parameters, 1 given in on line 143'
The other is fatal error message that states: 'Uncaught Error: Call to a member function bind_param() on null in sinsert.php:144 Stack trace: #0 {main} thrown in sinsert.php on line 144'
And I have no idea what they mean or how to solve them
2.I also cannot insert the inputted data in the database.My guess is due to the error messages above.But I don't actually know the real reason
I'd like to know how can I solve the above problems.I'm really grateful if you helped
Bonus Question:How can I prevent double booking,like no records should have the same room and same time
Your main issue is you are running the DB stuff even if the form is not submitted. The PHP code at the bottom.
I cleaned it all up for you:
<?php
if(!empty($_POST)){
$errors = [];
$date = empty($_POST["date"]) ? false : (new DateTime($_POST["date"]))->format('Y-m-d');
if(!$date) $errors["date"] = "*Please set a Date of the lesson";
$room = empty($_POST["room"]) ? false : $_POST["room"];
if(!$room) $errors["room"] = "*Please pick a room";
$tid = empty($_POST["tid"]) ? false : $_POST["tid"];
if(!$tid) $errors["tid"] = "*Please pick a Teacher";
$noofstu = empty($_POST["noofstu"]) ? false : trim($_POST["noofstu"]);
if(!$noofstu) $errors["noofstu"] = "*Please set the number of students that are attending";
$start = $_POST["start"];
$end = $_POST["end"];
$subj = $_POST['subj'];
if(empty($errors)){
$conn = mysqli_connect("localhost","root","","sba");
if(mysqli_connect_errno()) die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "INSERT INTO booking (date, room, tid, subj, start, end, noofstu) Values (?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param( $date, $room, $tid, $subj, $start, $end, $noofstu);
$stmt->execute();
if(!mysqli_query($conn, $sql)) $errors["DB"] = "Dateabase error!";
}
}
?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Booking Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id='frm'>
<form action="" method="post" >
<p>
<h1><u>Lesson Booking Form</u></h1>
<span class="error"><?php echo isset($errors['DB']) ? $errors['DB'] : '';?></span>
</p>
<p>
<label>Date of Lesson:</label>
<input type="date" name="date" >
<br><span class="error"><?php echo isset($errors['date']) ? $errors['date'] : '';?></span>
</p>
<p>
<label>Room:</label><br>
<input type="radio" name="room" value="246"/> Room 246
<input type="radio" name="room" value="340"/> Room 340
<input type="radio" name="room" value="342"/> Room 342<br>
<span class="error"><?php echo isset($errors['room']) ? $errors['room'] : '';?></span>
</p>
<p>
<label>Teacher in charge:</label><br>
<input type="radio" name="tid" value="T001"/>Mr.Williams
<input type="radio" name="tid" value="T002"/>Mr.Zimmerman
<input type="radio" name="tid" value="T003"/>Ms.Alcott<br>
<span class="error"><?php echo isset($errors['tid']) ? $errors['tid'] : '';?></span>
</p>
<p>
<label>Subject:</label>
<select name="subj">
<option value="unitA">Unit A</option>
<option value="unitB">Unit B</option>
<option value="unitC">Unit C</option>
<option value="unitD">Unit D</option>
<option value="unitE">Unit E</option>
<option value="unitF">Unit F</option>
</select>
</p>
<p>
<label>Starting Time:</label>
<select name="start" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="10:00:00">10:00</option>
<option value="11:00:00">11:00</option>
<option value="12:00:00">12:00</option>
<option value="13:00:00">13:00</option>
<option value="14:00:00">14:00</option>
<option value="15:00:00">15:00</option>
<option value="16:00:00">16:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>Ending Time:</label>
<select name="end">
<option value="10:00:00">10:00</option>
<option value="11:00:00">11:00</option>
<option value="12:00:00">12:00</option>
<option value="13:00:00">13:00</option>
<option value="14:00:00">14:00</option>
<option value="15:00:00">15:00</option>
<option value="16:00:00">16:00</option>
<option value="17:00:00">17:00</option>
<option value="18:00:00">18:00</option>
</select>
</p>
<p>
<label>Number of Students Attending:</label>
<input type="number" name="noofstu" min="1" max="40"><br>
<span class="error"><?php echo isset($errors['noofstu']) ? $errors['noofstu'] : '';?></span>
</p>
<p>
<input type="reset" id="reset" value="Reset">
<input type="submit" id="submit" value="Submit">
</p>
</form>
</div>
</body>
</html>
There is too much really to cover, but the (condition) ? true : false; style is called a ternary statement. In PHP7 some of these could be replace with null coalesce operator ?? For example this:
$room = empty($_POST["room"]) ? false : $_POST["room"];
Can be done in PHP7 as
$room = $_POST["room"] ?? false;
A few other things are.
Keep your PHP code together if possible (makes it cleaner)
don't modify data, sanitize display. You are not displaying any user input here.
most of your inputs are not free form types. So you are doing more work then you need to (assuming function ($data) actually did anything beside cause a syntax error)
use arrays for similar types of data $errors
do not echo strings outside of HTML ( echo "Not Inserted!"; ), its ugly
end you code with HTML tag (it was missing)
don't mix quoting styles in HTML (because it irritates me)
properly indent your code, (easier to read)
don't set variable more times then you need to, it's ugly (makes it hard to read)
Database date format is Y-m-d not m/d/Y Using Date time will handle multiple formats, and put them how you need them.
be lazy, don't write code you don't need to. I was half tempted to make some loops for the <select> options, but alas It was easier to copy them. Mainly I didn't feel like explaining str_pad to add the leading 0's on the time.
use CSS not content for styling multiple times vs style="margin-right:15px" it's more precise and easier to edit.
It wasn't all bad at least you had this prepare. Also just FYI, I haven't used Mysqli in about 4 years. I mainly use PDO, so I left the DB code as is.
PS I can't really test this, so forgive me any typos
Bonus Question:How can I prevent double booking,like no records should have the same room and same time
Make room, date, start and end a compound unique key in the DB (a key that has multiple fields in it), then it will throw an error when the same data is entered. In other words when the same room is booked for the same date and times. In PDO you could use exception handling try/catch to catch those errors in Mysqli as I said I haven't used in a long time. But I imagine you'd get an error for execute. You forgot same date in same room and same time so I added that in. Because you store the date and time separately it matters.
Another way to store these would be to get rid of the date field and change Start and End to DateTime in the DB. And change this:
$start = $_POST["start"];
$end = $_POST["end"];
To
$start = $date.' '.$_POST["start"]; //2018-10-14 09:00:00
$end = $date.' '.$_POST["end"];
This way you can store the date as part of the time. Also in the future if a class spanned more then one day, you would be all set. Because you could have it start today and end tomorrow. It would also be a bit easier to work with in SQL, because of the DATE(field) and other date related functions.
Related
I am trying to update the table below timetable, I want to be able to input the day and subject to change via a selection box form and "add" another id (say 103) to ethics on tuesday at 2pm.
With my current code i am selecting the options in the selection form but it when submitted it returns a value of Ethics Ethics Ethics Ethics Ethics (5 times). Like so- 5x Returned Value
Also when i get into the page i get the following errors...
Notice: Undefined index: day in
/Applications/XAMPP/xamppfiles/htdocs/assignment/stuTimetable.php on
line 304
Notice: Undefined index: subject in
/Applications/XAMPP/xamppfiles/htdocs/assignment/stuTimetable.php on
line 305
Any help is greatly appreciated.....
PHP
$day = $_POST['day'];
$subject = $_POST['subject'];
$sqlevent = "SELECT '$subject' FROM timetable WHERE Day = '$day'";
$resultevent = mysql_query($sqlevent);
$row2 = mysql_fetch_row($resultevent);
$resultevent2 = $row2[0];
echo $resultevent2;
if($resultevent2 = true){
$sqlevent2 = "UPDATE timetable SET 9am = 'Hello' WHERE Day = '$day'";
}
<form action="<?php $_PHP_SELF ?>" id="showapp" method="POST">
<input name="submitapp" type="submit" value="Show Appointments">
</form>
<br>
<form action="<?php $_PHP_SELF ?>" id="timeForm" method="POST">
<h1>Book a slot:</h1>
<br>
Day:
<br>
<select name="day" form="timeForm">
<option value="">--Select--</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
</select>
<br>
Subject:
<br>
<select name="subject" form="timeForm">
<option value="">--Select--</option>
<option value="Meta-Physics">Meta-Physics</option>
<option value="Moral Theory">Moral Theory</option>
<option value="Ethics">Ethics</option>
<option value="Baking">Baking</option>
<option value="Appointment">Appointment</option>
</select>
<br>
Password:
<br>
<input type="password" name="password" placeholder="Type Password to Confirm Booking">
<br>
<input name="submit" type="submit" value="Submit">
</form>
You're getting this error because:
$day = $_POST['day'];
$subject = $_POST['subject'];
are executed once you load the page and at the first time these array elements are not defined.
It's only when you submit the form where $_POST is going hold the right values. So you have to check if you're coming from a form submit
if(isset($_POST['sumbit'])) {
// the update code here
}
Note that I've use submit. You usually have to check any required field because if the field is empty any element of the indexed array would use this field's name as and array key.
Check first if you are handling a post request using something like
if(isset($_POST['day'])) {
// the update code here
}
I have this following codes.How do i send this form to php so in php i can access it like studentName course2 year3.Basically i have a table which looks like this studentName|course|year.I am looking for the right way to organize the data in order to insert it to my table.I have tried sending the form not as an array but i have to write 3 queries to insert 3 inputs.Is there any way to loop through the data and insert?
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="clg"/><br/>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="button" value="search" id="btn"/>
</form>
Here is what i have in php--
if(isset($_POST['name']) && isset($_POST['taskOpen'])
&& isset($_POST(['year'])){
$name=$_POST['name'],$course=$_POST['taskOpen'],$year=$_POST['year']
}
else {
echo "something";
}
foreach($name as $student){
$sql=$conn->prepare("INSERT INTO `student`(`studentName`) VALUES(:s_n)");
$sql->execute(array(":s_n"=>$student));
}
foreach($course as $courseN){
$sql=$conn->prepare("INSERT INTO `student`(`course`) VALUES(:co)");
$sql->execute(array(":co"=>$courseN));
}
foreach($year as $yearD){
$sql=$conn->prepare("INSERT INTO `student`(`year`) VALUES(:ya)");
$sql->execute(array(":ya"=>$yearD));
}
Here is what i think you are going for...
HTML
<!-- THE NAMES OF INPUT ELEMENTS WRAPPED IN A college_data-->
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]"/><br/>
<label>Student:-</label><input type="text" name="college_data[name]" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year1]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year2]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="submit" value="search" id="btn"/>
</form>
PHP
<?php
$college = isset($_POST['college_data']['clg']) ? htmlspecialchars(trim($_POST['college_data']['clg'])) :null;
$studentName = isset($_POST['college_data']['name']) ? htmlspecialchars(trim($_POST['college_data']['name'])) :null;
$studentName2 = isset($_POST['college_data']['name2']) ? htmlspecialchars(trim($_POST['college_data']['name2'])) :null;
$taskOpen1 = isset($_POST['college_data']['taskOpen1']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen1'])) :null;
$taskOpen2 = isset($_POST['college_data']['taskOpen2']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen2'])) :null;
$year1 = isset($_POST['college_data']['year1']) ? htmlspecialchars(trim($_POST['college_data']['year1'])) :null;
$year2 = isset($_POST['college_data']['year2']) ? htmlspecialchars(trim($_POST['college_data']['year2'])) :null;
// TEST::: DELETE EVERYTHING BELOW THIS LINE ONCE YOU ARE DONE CONFIRMING THAT IT IS OK
// CLICK THE SUBMIT BUTTON TO SEE THE VALUES REFLECTED HERE AS SOON AS THE FORM GETS SUBMITTED...
var_dump($college);
var_dump($studentName);
var_dump($studentName2);
var_dump($taskOpen1);
var_dump($taskOpen2);
var_dump($year1);
var_dump($year2);
?>
VALIDATION
<?php
// FIRST CREATE AN ARRAY TO HOLD MESSAGES TO BE SHOWN TO THE USER
// SHOULD ANYTHING GO WRONG... & ALSO AN EMPTY ERROR MESSAGE STRING...
$arrErrorBag = array();
$strErrorMsg = "";
if(isset($_POST['submit'])) {
// LET'S ASSUME FOR THE MOMENT YOU HAVE SPECIAL CONSTRAINTS
// TO BE APPLIED TO EACH FIELD DURING YOUR VALIDATION PROCESS.
// WE WILL USE SIMPLE REGULAR EXPRESSIONS HERE FOR DEMONSTRATION
// BUILD VALIDATION REG-EXES FOR THE FIELD:: WE WANT ONLY A MINIMUM OF 10 CHARACTERS FOR STUDENT & COLLEGE
// AGAIN; YOU CAN GO WILD BUT WE ARE KEEPING IT SIMPLE
// PLUS, DOING IT LIKE THIS IS JUST SO THAT YOU GET THE DRIFT... ;-)
$rxColStudent = "#(.){10,}#si";
// FOR THE SELECTS, WE KNOW THAT THE VALUES ARE NUMBERS
// WHICH ARE BETWEEN 1 & 4; BUT WE TAKE IT TO "BETWEEN 1 & 9"
// AND WE INTEND USING ONE REGEX FOR ALL OF THEM SINCE THEY ARE SIMILAR.
$rxCourseYear = "#\d#";
// NOW WE HAVE THE REGEXES: THEN WHAT?
// VALIDATION BEGINS... ;-)
// TO MAKE IT EASIER ON OURSELVES, WE BUNDLE ALL THE STUDENT, STUDENT1 & COLLEGE FIELDS
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
// VALIDATE COLLEGE, STUDENT & STUDENT2...
$arrStringValFields = array(
"student" => array("Student Nr. 1", $studentName),
"student2" => array("Student Nr. 2 ", $studentName2),
"college" => array("College", $college),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrStringValFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxColStudent, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to have a minimum of 10 Characters. Please, check that you have not missed something.";
}
}
// TO MAKE IT AGAIN EASIER ON OURSELVES, WE BUNDLE ALL OTHER FIELDS THAT HAVE NUMERIC VALUES
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
$arrNumericFields = array(
"taskOpen1" => array("Open Task Nr. 1", $taskOpen1),
"taskOpen2" => array("Open Task Nr. 2 ", $taskOpen2),
"year1" => array("College Year Section 1", $year1),
"year2" => array("College Year Section 2", $year2),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrNumericFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxCourseYear, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to be a Single Digit & it should. Did you try to *NUKE OUR ASSES OFF*. Please, don't. We are your Brothers ;-)";
}
}
// MAMA MIA!!! SO MUCH FOR A SIMPLE 6-FIELD VALIDATION...
// HAPPILY ENOUGH; WE ARE THERE... ONLY; NOT JUST YET...
// CHECK THE ERROR BAG TO SEE IF IT CONTAINS ANYTHING.
// IF IT DOES; THEN WE HAVE TO FIND A WAY TO DISPLAY THIS TO THE END-USER.
if (!empty($arrErrorBag)) {
// TURN THE ERROR BAG ARRAY TO A STRING & ASSIGN IT BACK TO THE ERROR MESSAGE STRING FOR DISPLAY...
$strErrorMsg = "<span class='has-error'>" . implode("</span><br /><span class='has-error'>", $arrErrorBag);
}
else {
// WE HAVE REACHED THE CLIMAX OF OUR POLICE-WORK...
// SO WE EITHER STORE THE DATA TO THE DATABASE TABLE OR
// WE BAKE & CAKE IT FOR CHRISTMAS - YOUR CALL ;-)
}
}
?>
Now, that's OK. But how does the User get to know that there were Errors and how does s/he avoid typing-in the same information over again?
Our HTML File should have been built earlier to take that into consideration, but then again, EINTEIN WAS RIGHT!!! Human Stupidity is totally as Infinite as the Universe... but that's why we are here, right? To cut down the infinitude of our Stupidity and grow into real Humans;-) So we revise our HTML to take these into account.
HTML - REVISED: UNLEASH THE DRAGON!!!
<!-- WE ADD A SLOT FOR OUR ERROR MESSAGE: JUST BEFORE THE FORM. -->
<div class="error-slot"><?php echo $strErrorMsg; ?></div>
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]" value="<?php echo $college; ?>" /><br/>
<label>Student:-</label><input type="text" name="college_data[name]" value="<?php echo $studentName; ?>" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1" <?php if($taskOpen1=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen1=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen1=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen1=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year1]">
<option value="1" <?php if($year1=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year1=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year1=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year1=="4"){echo "selected";} ?>>year4</option>
</select>
<label>Student:-</label><input type="text" name="college_data[name2]" value="<?php echo $studentName2; ?>" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1" <?php if($taskOpen2=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen2=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen2=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen2=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year2]">
<option value="1" <?php if($year2=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year2=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year2=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year2=="4"){echo "selected";} ?>>year4</option>
</select>
<input type="submit" value="search" name="submit" id="btn"/>
</form>
From your table design in the database it looks like you want to insert a student, their course and the year they are taking it in. Unless you are going to validate the form so that the number of students matches the number of courses and numbers of years so you can easily loop and insert based on their indexes, i don't see how it can be easily done.
Example:
$_POST = Array(
'name' = Array ( 'Kelly', 'Tom', 'Jack' ),
'course' = Array ( 'Course1', 'Course2', 'Course3' ),
'year' = Array ( '2007', '2008', '2009' ),
);
for ( $i = 0; i < count($_POST['student_name']); i++ ) {
$sql = sprintf("INSERT INTO test ( student_name, course, year ) VALUES ( %s, %s, %d )",
$_POST['student_name'][$i], $_POST['course'][$i], $_POST['year'][$i]
);
$conn->query($sql);
}
I am working on a form to create an athlete forename and surname. This works as it should, populating the appropriate parts of the database.
I have now come to add a drop down box in which they will select the athlete's country. Unfortunately, I cannot get this to show up in the athletecountry field of the database. This is in the same table as forename and surname.
I would hugely appreciate any help.
<?php echo ($error != "") ? $error : ""; ?>
<form action="createathlete.php" method="post">
<br>
<br>
Athlete Forename: <input type="text" value="<?php echo $athleteforename; ?>" name="athleteforename" /><br/>
Athlete Surname: <input type="text" value="<?php echo $athletesurname; ?>" name="athletesurname" /><br/>
Representing: Country: <select name=$athletecountry tabindex="1">
<optgroup label="Continent">
<option value="Country 1">Country 1</option>
<option value="Country 2">Country 2</option>
<option value="Country 3">Country 3</option>
</optgroup>
</select>
<input type="submit" value="Register" name="submit-form" />
</form>
Earlier in the page I also have this code which I cobbled together from a couple of other tutorials.
//initialize php variables used in the form
$athleteforename = "";
$athletesurname = "";
$userID = "";
$athletecountry = "";
//check to see that the form has been submitted
if(isset($_POST['submit-form'])) {
//retrieve the $_POST variables
$athleteforename = $_POST['athleteforename'];
$athletesurname = $_POST['athletesurname'];
$athletecountry = $_POST['athletecountry'];
//initialize variables for form validation
$success = true;
$userTools = new UserTools();
//prep the data for saving in a new user object
$data['athleteforename'] = $athleteforename;
$data['athletesurname'] = $athletesurname;
$data['athletecountry'] = $athletecountry;
$data['userID'] = $user->id;
//create the new user object
$newAthlete = new Athlete($data);
//save the new user to the database
$newAthlete->save(true);
It seems you are not giving proper name to select i.e $athletecountry
<select name=$athletecountry tabindex="1">
change to
<select name="athletecountry" tabindex="1">
As per #Chandu and #taxicala answers, once the code is showing as "athletecountry" that should be fine.
Check that the Athlete() class is expecting all the elements in the array, perhaps the country string is being dropped because it's unexpected for some reason?
You have a typo in the name attr of the select:
Change:
<select name=$athletecountry tabindex="1">
To:
<select name="athletecountry" tabindex="1">
I'm trying to write some PHP code that adds data submitted via a form into a database table I have created. It works great - once. Once I have submitted data and added it to the database via the form once already it will no longer work. I'm thinking it's a problem with the function I have written as when using var_dump(); on the variables I'm submitting in the form they all come out fine.
I'd appreciate any suggestions you guys might have, thanks!
<form action="" method="post">
<label for="habbo_name"><center><b>Habbo Name:</b></label><br >
<input type="text" name="habbo_name" size="30">
<b><center>Transfer Status:<br ><select name="transfer_status">
<option value="Stage Five">Stage Four - Rejected</option>
<option value="Stage Four">Stage Four - Accepted</option>
<option value="Stage Three">Stage Three</option>
<option value="Stage Two">Stage Two</option>
<option value="Stage One" selected="selected">Stage One</option>
</select>
<label for="date"><center><b>Date:</b></label><br >
<input type="text" name="date" size="30"><br />
<input type="Submit"><br /><br />
</form>
Go back
<?php
if (empty($_POST) === false) {
$habbo_name = $_POST['habbo_name'];
$transfer_status = $_POST['transfer_status'];
$date = $_POST['date'];
add_transfer($habbo_name, $transfer_status, $date);
header('Location: moderate.php');
exit();
}
?>
Function:
function add_transfer($habbo_name, $transfer_status, $date) {
global $con;
$query = "INSERT INTO `transfers` SET `habbo_name`='$habbo_name', `transfer_status`='$transfer_status', `date`='$date'";
$update = $con->prepare($query);
$update->execute();
}
You have syntax error in insert query, use it like below
$query = "INSERT INTO `transfers` (`habbo_name`,`transfer_status`,`date`) VALUES ('$habbo_name', '$transfer_status', '$date')";
I don't think there's anything I left out, but the form doesn't seem to be transmitting any data upon hitting submit. My code is as follows, I realize it's kind of long, but I wanted to include the entire form. All of the attached functions just check if the input was valid:
<form name="formname" id="formname" action="database.php" method = post onsubmit="return checker()">
Username: <input type='text' id='un' onchange="checkname(id)" onkeyup="checkempty(id)" ><div id="un1"></div><br>
Reporter Title:<br>
<select id="s2" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="Assistant Director">Assistant Director</option>
<option value="Director">Director</option>
<option value="DB Admin">DB Admin</option>
<option value="Systems Admin">Systems Admin</option>
</select><div id="s21"></div>
<br>
Password: <input type='password' id='pw' onchange="checkpass(id)" onkeyup="checkempty(id)"><div id="pw1"></div><br>
Email: <input type='text' id='eml'onchange="checkemail(id)" onkeyup="checkempty(id)"><div id="eml1"></div><br>
Description:<br> <textarea rows="6" cols="20" id="desc" onchange="checkdesc(id)" onkeyup="checkempty(id)" ></textarea><div id="desc1"></div><br>
Type of Incident:<br>
<select id="s1" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="afs">afs</option>
<option value="password">password</option>
<option value="hardware">hardware</option>
<option value="other">other</option>
</select><div id="s11"></div>
<br>
<?php
include("connect.php");
$ret = mysql_query("SELECT * FROM countries");
echo "Choose your location:<br>";
echo "<select id='countries' onblur='checktype(id)'>";
echo "<option value='choose'>Choose one</option>";
while($array = mysql_fetch_array($ret)){
echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";
}
echo "</select><br>";
?>
<div id="countries1"></div><br>
<p>
Would you like an email copy?
<select id="s3">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<input type="submit" id = "sub" value= "Submit">
</p>
</form>
and the php I tried to receive it with
<?php
include("connect.php");
$username = $_GET['un'];
$password = $_GET['s2'];
$reporter = $_GET['pw'];
$email = $_GET['eml'];
$description = $_GET['desc'];
$type = $_GET['s1'];
$country = $_GET['countries'];
$emailopt = $_GET['s3'];
?>
the checker function:
function checker(){
if(isgood && isgood1 && isgood2 && isgood3 && isgood4 && isgood5 && isgood6)
{
return true;
}
else{
document.getElementById('subb').style.visibility="visible";
document.getElementById('subb').innerHTML = "You must fully complete the form.";
return false;
}
where the "isgoods" where just quick flags I made for validations, which was all working properly.
Your form's method is POST so you should use $_POST instead of $_GET in your PHP script.
Also you should fix up your HTML so it's valid, you need to quote the method attribute properly:
<form name="formname" id="formname" action="database.php" method="post" onsubmit="return checker()">
Well, I feel stupid. The problem was that I didn't give my HTML elements names, but rather just IDs. I was so used to using ajax and submitting by just getting the value with javascript via the ID that I forgot about names O.o
You are submitting your form with method="POST", so in your PHP you need to read the POST values:
$username = $_POST['un'];
...
Had you submitted your form with method="GET", your PHP code would work. Read about the difference here.