Update Table using PHP & SQL - php

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
}

Related

Booking system with php and mysql

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.

set values as a variable of select tag in php

I want to set both values as variable. Means if I want to use sales or training as a variable and if I want to use its value anywhere then I can use it.
<form action="code.php" method="post">
<select name="department">
<option>Please Choose Department</option>
<option value="sales">Sales</option>
<option value="training">Training</option>
</select>
<input type="submit" value="submit">
</form>
I am trying by below code but I can't.
code1.php
<?php
$stud = explode("_", $_POST['department']);
$sales = $stud[0];
$training = $stud[1];
echo "$sales";
echo "$training";
?>
$sales and $training are not working as variable.
Please help.
Probably you are looking for this:
<form action="code.php" method="post">
<select name="department[]" multiple>
<option>Please Choose Department</option>
<option value="sales">Sales</option>
<option value="training">Training</option>
</select>
<input type="submit" value="submit">
</form>
<?php
$sales = $_POST['department'][0];
$training = $_POST['department'][1];
echo $sales;
echo $training;
?>
select must be defined as multiple select and as array in name.
Update
<select name="department">
With
<select name="department[]" multiple>
PHP Part
<?php
$stud = $_POST['department'];
extract($stud);
echo $sales;
echo $training;
?>
Explanation:
We have used multiple attribute of <select> so that multiple options can be selected.
If we use multiple as select, the value getting posted as array. So, no need to explode it.
Then we extract() ed the posted array to get two desired elements.

PHP - Saving a dropdown box into my mysql database

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">

how extract data inputted using form and display it using php in table

I am not sure how to go about doing this, but I have an assignment tomorrow and i'm new in php i have to put in the html part a text box and check bob and radio button and drop down list and then take data from user and then extract data in php and display it in table also using php . Any one can helps me please
file.html
<form action="file.php" method="post">
Name:<input type="text" name="name"><br>From<br>
<input type="radio" name="from" value="us">US<br>
<input type="radio" name="from" value="else">Else<br>
<select name="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected>Fiat</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
file.php
<?php
$name = $_POST['name'];
//this takes the data from input
$from = $_POST['from'];
$car = $_POST['car'];
echo "<table><tr><td>Name</td><td>From</td><td>Car</td></tr>
<tr><td>".$name."</td><td>".$from."</td><td>".$car."</td></tr></table>";`
?>
This will return a table with the inserted values.

Confused why form is not submitting

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.

Categories