PHP Form not posting to a MySQL database - php

I'm creating a new booking system for my employer, in which a form is filled in and data enters a pre-built MySQL database.
I'm honestly unsure as to what I am doing wrong. Originally the data would not post into the database, but the form would appear to have submitted. Now, the form just submits to a white page. I will submit the full page code below as there's no comprimising data there, and hopefully somebody will be able to help.
<head>
<title> Moat Laptop Bookinge </title>
<?php
if (isset($_POST['submitted'])) {
include('booking_db.php');
$name = $_POST['name'];
$out = $_POST['out'];
$in = $_POST['in'];
$sqlinsert = "INSERT INTO Future (name, out, 'in') VALUES ('$name', '$out', '$in')";
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
?>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<script>
$(document).ready(function() {
$("#datepicker2").datepicker();
});
</script>
</head>
<body style="background-height: 100%;background-width: 100%;background: #141E30;background: -webkit-linear-gradient(to left, #141E30 , #243B55);background: linear-gradient(to left, #141E30 , #243B55);">
<div id="logo" style="font-family: Tw Cen MT; font-weight: Bold; position: fixed; color: white; left: 650px;top: 35px; font-size: 80px;text-shadow: 3px 3px #c7c7c7;">
Book a Laptop
</div>
<div id="content_box" style="background-color: white;position: fixed; left: 450px;top: 135px; width:60%; height: 70%; border-radius: 3px;">
<center>
<form method="post" action="book.php" style="font-family: Bodoni MT;">
<input type="hidden" name="submitted" value="true" />
<br />
<br />
<b><legend>First Name and First Letter of Surname</legend></b>
<input type="text" name="name" value="Ex. James T" />
<br/>
<br />
<b><legend>When will you need to collect the device?</legend></b>
<input id="datepicker2" name="out" />
<br/>
<br />
<b><legend>When will you return the device?</legend></b>
<input id="datepicker" name="in" />
<br />
<input type="submit" value="Confirm Booking" />
</center>
<?php
echo $newrecord
?>
</div>
</body>
If you need any more information, within reason, feel free to ask.
EDIT
This issue has been resolved, I cannot mark the answer as it was my answer and I have to wait 2 days. THank you for all of the answers.

There could be a problem in the line include('booking_db.php');. You should mention error_reporting(E_ALL); at the top of the page, and try debugging:
error_reporting(E_ALL);
if (isset($_POST['submitted'])) {
var_dump(file_exists('booking_db.php')); //check if you get true or false
require 'booking_db.php'; // Change include to required
echo "Test";
exit;
$name = $_POST['name'];
echo $name; // Check
$out = $_POST['out'];
$in = $_POST['in'];
$sqlinsert = "INSERT INTO Future (name, out, 'in') VALUES ('$name', '$out', '$in')";
var_dump($dbcon); // check
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
Please check what you're getting after form submit.

Replace your insert query with :
INSERT INTO Future
(`name`,`out`,`in`) VALUES ('".$name."', '".$out."', '".$in."')
and
if (isset($_POST['submitted'])) with if (isset($_POST['Confirm Booking']))
because you have to put your value of submit button in POST

Turns out, my issue was with
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
I changed this to
if (mysqli_query ($link, $sqlinsert)) {
echo "";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
And changed a few variables to match up with this, and it started working and posted to my DB. Thank you to anyone who answered.

Related

change input box value according to variable php and html

I am making a PHP project and am trying to change an input boxes value according to a PHP variable, how would I do this? So far, when I try to change the input boxes value it just changes the value to the name of the variable.
Here's the html for that section:
echo '
<html>
<title>Ramen</title>
<body>
<h1>
<p>Welcome to NoteBook!</p>
<form method="post">
<p>File Name:<input type="text" name="fname"></p>
<p>Type Here:<input type="text" name="content" id="TextBox" value="<?php echo $value; ?>"><p>
<p>Save:<input type="submit" value="Save"></p>
</form>
<form method="post">
<p>File to Open: <input type="text" name="filename"></p>
<input type="submit" value="Open">
</form>
</h1>
</body>
<style>
body{
background-color:#66b3ff;
}
p{
margin-left:30px;
}
h1{
background-color:white;
height:600px;
border-radius:1px;
font-size:18px;
font:italic;
}
#TextBox{
height:500;
width:700;
}
{
</style>
</html>```
$value doesn't appear to be being set anywhere.
I'm also a little confused as to why you have two <form>s.
As a starter, you need to parse the values coming in from the form, for example:
<?php
if (isset($_POST["filename"]) { // The $_POST variables are set using the name element of the <input> tag
$value = $_POST["filename"]
}
?>
You would likely want to do some more validation on the content of $_POST["value"] before accepting it.
Perhaps take a look at this example to get you started.
I leave you a possible example with explanation.
Besides, I have adapted the HTML structure a bit, since it has serious formatting problems. I advise you to read the manual on how to use the labels.
I added the name attribute to the submit, in order to know if the form is defined:
<input type="submit" name="save_data" value="Save">
Example:
<?php
// reset ¡important! (avoid warning <b>Warning</b>: Undefined variable etc..)
$file_name = $content = $txt_content = '';
// Recomended to check if the form is define
if (isset($_POST['save_data'])) {
// Get the inputs data
$file_name = $_POST['fname'] ?? '';
$content = $_POST['content'] ?? '';
// You can use textarea
$txt_content = $_POST['txt_content'] ?? '';
// Data is true
if ($file_name && $content && $txt_content) :
// Do somenting (ex: save it in DB)
//
//
$success = "Save correctly: $file_name";
// Data is empty (optional)
else :
$error = 'Te fields are empty.';
endif;
}
?>
<html lang="en-EN">
<head>
<title>Ramen</title>
<style>
body{
background-color:#66b3ff;
}
p {
margin-left:30px;
}
.wrapper {
background-color:white;
height:600px;
border-radius:1px;
font-size: 1rem;
font:italic;
padding: 1rem;
}
textarea {
height:200px;
width:400px;
}
.error {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Welcome to NoteBook!</h1>
<form method="post">
<lable for="fname">File Name:</lable>
<input type="text" name="fname" id="fname" value="<?php echo $file_name; ?>"></p>
<label for="content">Type Here:</label>
<input type="text" name="content" id="content" value="<?php echo $content; ?>">
<!-- for the content you could use the textarea tag -->
<textarea name="txt_content"><?php echo $txt_content; ?></textarea>
<input type="submit" name="save_data" value="Save">
<?php if (isset($error)) echo '<p class="error">' . $error . '</p>'; ?>
<?php if (isset($success)) echo '<p class="success">' . $success . '</p>'; ?>
</form>
</div>
</body>
</html>

Running PHP in HTML error (This page isn’t working)

I setup this signup form for my website. People enter their username, email and password and then it uses php to add it to my database. But I keep getting this error when I run my code. My html file is on my AWS server as well as this PHP file, so I believe there must be an error in my code. I am still very new to PHP.
HTML:
<form method="get" action="signup_form.php">
<input style="width: 300px; display: block; margin-left: auto; margin-right: auto;" type="text" name="signup_name" placeholder="Screen Name">
<br>
<input style="width: 300px; display: block; margin-left: auto; margin-right: auto;" type="text" name="signup_mail" placeholder="Your E-mail">
<br>
<input style="width: 300px; display: block; margin-left: auto; margin-right: auto;" type="password" name="signup_password" id = "password" placeholder="Create Password" required>
<br>
<input style="width: 300px; display: block; margin-left: auto; margin-right: auto;" type="password" name="confirm_password" id = "confirm_password" placeholder="Repeat Password" required>
<br>
<br>
<button onclick="validatePassword()" class="button" style="display: block; margin-left: auto; margin-right: auto;" type="submit" name="submit_login">
SUBMIT
</button>
</form>
and here is my PHP code:
<?php
$signup_name = filter_input(INPUT_GET, 'signup_name');
$signup_mail = filter_input(INPUT_GET, 'signup_mail');
$signup_password = filter_input(INPUT_GET, 'signup_password');
if (!empty($signup_name)){
if (!empty($signup_mail)){
$host = "wildwea.......onaws.com";
$dbusername = "a....in";
$dbpassword = ".Bi....4.";
$dbname = "innodb";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else{
$sql = "SELECT EXISTS (SELECT 1 FROM Users WHERE Email = $signup_mail);"
if ($sql = 0){
$sql = "INSERT INTO Users (Username, Email, Pword)
values ('$signup_name', '$signup_mail',md5('$signup_password'))";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
} else {
echo "User already in database";
}
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>
If you want to see the error here is the link to the sign up page:
http://thewildwear.com/signup.html
We can't see your specific error (looks like there might be multiple) so we won't be able to help you out there. But I could make a suggestion about how to structure your script.
Caveat - this really isn't a good approach for anything but the smallest of applications or for learning.
The main idea is that there is only 1 script and it has processing and display sections. It will only go into the processing section when the form is actually submitted.
If there are any validation errors, it will fall through to the display section and list out the errors and the form.
If there are no validation errors, it will save to the DB and redirect to some other page.
As you develop bigger (and better) applications, you might find that this type of coding will quickly become unwieldy - you're mixing validation, SQL, views/display, etc. all in a single script. They will become more complex and before long you'll have a big ball of spaghetti. Once you hit this point, start looking into frameworks.
But for now, keep on going. Good luck.
<?php
// A list of validation errors. Initialize to an empty list.
$errors = [];
/****************************/
/******** PROCESSING ********/
/****************************/
// The form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Values submitted from form
$name = $_POST['signup_name'];
$email = $_POST['signup_mail'];
$password = $_POST['signup_password'];
// Validation
if (empty($name)) {
$errors[] = 'Please enter your name';
}
if (empty($email)) {
$errors[] = 'Please enter your email';
}
// ... check if email already exists in your DB.
// ... more validation here
// There are no validation errors, process the form.
if (empty($errors)) {
// At this point, you now have a valid form. Just save it to the DB.
// Redirect to somewhere
}
}
/****************************/
/********** DISPLAY *********/
/****************************/
if (count($errors) > 0) : ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- Use "post" and remove action and it will post to itself. -->
<form method="post">
<!-- ... -->

PHP retrieve data from database and show in text area

I m trying to display retrieved data from the database in the earlier created text area. Code is supposed to get users nickname and input message, store both in database and retrieve it back to text area, smth similar to one man chat (whatever is typed after clicking 'Send message' should be stored to database and retrieved and shown in the text area). I am able to store into my database and display retrieved data anywhere outside the text area. Any help appreciated. Thank you!
Code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<center>
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</form>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
$query = mysql_query('select * from messages');
while ($entry = mysql_fetch_object($query))
{
printf("<p>%s <br />- <em>%s</em></p>",
htmlentities($entry->message),
htmlentities($entry->nickname)
);
}
?>
</body>
</html>
postmessage.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<?php
$nickname=$_POST['nickname'];
$message = $_POST['message'];
$nickname = mysql_real_escape_string($nickname);
$message = mysql_real_escape_string($message);
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
if (!mysql_query(
"insert into messages (nickname, message) VALUES ('$nickname', '$message')"
)){
echo ("Could not process your send request");
};
?>
<body>
</body>
</html>
UPDATED:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage1.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }?></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
post..php:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
</body>
</html>
For your form, I suggest the following:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }</textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
Then in your Post handler, do this:
<?php
start_session();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickName'] = htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
Taking this further, you can add TimeStamps via JS and you can use AJAX to post the data instead of using the form. Just drop the redirects and the session data. Also if the user closes the browser by accident, and returns, it should re-populate the data if the session is still alive.
Could also compile the chat and autosave it into DB every min or so instead of every chat action. Adding a leave button can kill the session and save everything to the DB at that time. Lots of ways to do it.
Code above is untested.
EDIT after comments
For your Chat page, I suggest changing the textarea to a div for better style control. Here is an example of the style: http://jsfiddle.net/Twisty/8frqcyyk/
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
.chatForm {
background: #ccc;
border: 1px solid #000;
width: 40em;
}
.chatForm ul {
padding: 0;
width: 30em;
margin: 5px auto;
}
.chatForm ul li {
list-style: none;
}
.chatForm ul li label {
display: block;
font: 1em Verdana, sans-serif;
}
.chatForm label.title {
background: #222;
border: 3px solid #222;
color: #FFF;
display: block;
font: 1em Verdana, sans-serif;
height: 1.5em;
margin: 0px auto;
width: 30em;
}
.center {
text-align: center;
}
.chatHistory {
background: #fff;
border: 1px inset #DDD;
display: block;
font: 1em Verdana, sans-serif;
height: 15em;
margin: 0px auto;
overflow-y: scroll;
padding: 2px;
text-align: left;
width: 30em;
}
.chatHistory p {
margin: 5px 0;
}
.chatHistory label {
display: inline-block;
font: bold 0.85em Arial, sans-serif;
width: 100px;
}
.chatHistory label.senderName {
color: blue;
}
.chatHistory label.nickName {
color: red;
}
.messageText {
width: 75%;
}
input[type='submit'] {
font: .85em Arial, sans-serif;
width: 20%;
}
</style>
</head>
<body>
<form method="post" action="postmessage.php">
<div class="chatForm">
<label for="output" class="center title">Chat History</label>
<div id="output" class="chatHistory">
<?php echo $_SESSION['currentChat']; ?>
</div>
<ul>
<li>
<label for="nickname">Nickname</label>
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
</li>
<li>
<label for="message">Type your message here:</label>
<input name="message" type="text" id="message" class="messageText" /><input type="submit" value="Send" /></li>
</ul>
</div>
</form>
</body>
</html>
A few changes for your Post handler too (that should not be wrapped in HTML):
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$results = $mysqli->query("SELECT * FROM messages");
$updateChat = "";
while($row = $results->fetch_assoc()){
$updateChat .= "<p><label>". htmlentities($row['nickname'] .":</label>";
$updateChat .= htmlentities($row['message']) . "</p>\r\n";
}
$results->free();
$mysqli->close();
$_SESSION['currentChat'] = $updateChat;
// Redirect back to display content
header("Location: chatform.php");
?>
If it were me, I would improve me DB schema. The table could include more columns: ID, DateStamp, Sender, Recipient, Message. Hope that helps, and again, untested.

How to insert data into database only when input are not empty?

I came up with a problem which made me crazy as I am new to PHP. The problem is: the below timetable submission form works good on Chrome (every time I left the email unfilled, the submission cannot be processed). However, when using on safari, you can always submit blank form into the database.
Here is the html form.
<script type="text/javascript" src="/membership/my-form/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/membership/my-form/js/main.js"></script>
<form class="mf-form floating-labels" method="post" action="timetablesubmit.php">
<div>
<h1 style="text-align:center">Availability form</h1>
</div>
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
</p>
<div>
<input name="location1" value="A" type="hidden">
<input name="location2" value="B" type="hidden">
</div>
<div class="AMY box">You work in A.</div>
<div class="TOM box">You work in B.</div>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Amy"){
$(".box").hide();
$(".AMY").show();
}
if($(this).attr("value")=="Tom"){
$(".box").hide();
$(".TOM").show();
}
});
}).change();
});
</script>
<style type="text/css">
.box{
padding: 10px;
display: none;
margin-top: 20px;
border: 1px solid #000;
font-size:1.6em;
text-align:center;
background-color: #f1f1f1;
}
</style>
Here is the timetablesubmit.php:
<?php
header("content-type:text/html;charset=utf-8");
session_start();
$timesubmit=date('Y-m-d H:i:s');
$staff=$_POST['timetable-staff'];
$email=$_POST['timetable-email'];
$con=mysql_connect("localhost","database","password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<? require 'header.php'; ?>
<div class="tk-reg">
<p>Thak you <?php echo $_POST['timetable-staff']; ?><p>
<p> Time availability submitted successfully.<p>
Your email address is: <?php echo $_POST["timetable-email"]; ?>
</div>
<div class="tk-regfollow">
<ul style="text-align:center">
Back to home page.
</ul>
</div>
</html>
Then I searched the Internet and changed to below, still not working on Safari (the alert appears, however data still been insert into database.
<?php
require 'header.php';
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["timetable-staff"])) {
$nameErr = "Please select a staff.";
} else {
$staff = test_input($_POST["timetable-staff"]);
}
if (empty($_POST["timetable-email"])) {
$emailErr = "Email address is required";
} else {
$email = test_input($_POST["timetable-email"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysql_connect("localhost","database_name","database_password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database_name", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<style>
.error {color: #FF0000;}
</style>
<h1 style="text-align:center">Availability form for
<?php
$d=strtotime("+1 Months");
echo date("M", $d) . " 2015 <br>";
?>
</h1>
<form class="mf-form floating-labels" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
<span class="error">* <?php echo $nameErr;?></span>
</p>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</html>
I hope someone could help me pointing out my mistakes. Thank you.
======================================================================
I tried a lot of ways to figure this out, however still have either 'this' or 'that' problems. I finally use a method that actually work, but I do not know whether it is not recommended.
Here is the code I modified in timetablesubmit.php
(my flow is: timetable.php ==>timetablesubmit.php==>welcome.php)
$email = trim($_POST['timetable-email']);
if($email !='' and $email !=null) {
$sql1;
}
else {
echo '<html><head>
<link rel="stylesheet" type="text/css" href="/membership/style.css"/>
<head>
<div class="check-error-message">
<p>Error: Email address is required.</p><br>
Return
</div>';
exit;
};
You can check with condition before insert operation
if($nameErr =="" && $emailErr == "")
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
you can have one condition here to avoid empty fill
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
here keep this condition like this
if($staff!='' && $email!='')
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
Html 5 "required" will not work in safari.
This line is the problem <input class="email" type="email" name="timetable-email" id="mf-email" required>
Write jquery/javascript validation to check the required field.
Hope its help you.
As they said, not all browsers accept the attribute required because it's new.
On PHP, server side, you can validate too if there's something filled with:
$var = trim($_POST['var']);
if(!is_empty($var)) {
//do mysqli function
}
else {
//show error
}
trim will remove blank spaces at start and end of the value given.
is_empty will be almost like $var == ""

How to create a Dynamic Phonebook with Groups functionality

I want to create an online phone book where user can add as many contact as he want and he must be able to create and divide those contact into groups. For eg. Friends, Family etc. All the groups must be created or deleted by the user. Can anyone help me..
Any good tutorial or a book reference will do. I will be using PHP, MySQL and a little bit of AJAX and jQuery.
Thanks
http://learning-computer-programming.blogspot.com/2008/05/creating-simple-phone-book-in-php.html will give u general idea for creating phone book.
For categorizing ur book u would be needing another table storing the nature and id of the group(group_table) which u can thru a field in main phone_table
config.php
<?php
$dbname = "phonebook"; // name of database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("phonebook") or die(mysql_error());
?>
add.php
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html>
index.php
<?php
include_once('config.php'); // call database login details page
if(isset($_POST['save'])) {
$name = strip_tags($_POST['username']);
$phone = strip_tags($_POST['phone']);
$town = strip_tags($_POST['town']);
$query = "INSERT INTO my_contacts(name,phonenumber,town) VALUES('$name', '$phone', '$town')";
$result = mysql_query($query);
if($result) {
echo "Data successfully stored!";
}
else {
echo "Data was NOT saved!";
echo "<p> Query: ' $query ' </p>";
}
}
$query = "SELECT * from my_contacts";
$result = mysql_query($query);
echo "<h3>My Contact's Data</h3>";
echo '<table border = "1">';
echo "<tr><td>Id</td><td>Name</td><td>Phone Number</td><td>Town</td></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>".$row['id']."</td><td><a href='index.php?ID=$row[id]'>".$row['name']."</a></td><td>".$row['phonenumber'].
"</td><td>".$row['town']."</td></tr>";
}
echo "</table>";
?>

Categories