Displaying input error messages next to the input field - php

I would like to display error checking next to the input field. Currently, errors are displayed at the top of the page.
Maybe there is some way to check for input errors?
I could not find a similar example where html and php code are separated into different files
Or my code is completely wrong.
index.php
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>testpage</title>
</head>
<body>
<?php
require('process.php');
?>
<h1>Form</h1>
<form method="post" action="">
<div> Date : <input type="date" name="date"/><br />
</div>
<div>
<label>Start:</label>
<select name="starttime" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>End:</label>
<select name="endtime">
<option value="18:00:00">18:00</option>
</select>
<br>
</div>
<div>
Name : <input type="text" name="user_name" placeholder="Name" /><br />
</div>
Mail : <input type="email" name="user_email" placeholder="Mail" /><br />
Message : <textarea name="user_text"></textarea><br />
<input type="submit" value="Send" />
</form>
<h3 class=" txt_center">DB Output <span id="curdate">
<?php require('calendar.php');
?>
<!-- <script type="text/javascript" src="js/time-select.js"></script> -->
</body>
</html>
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
$u_starttime = $_POST["starttime"];
$u_endtime = $_POST["endtime"];
$u_name = filter_var($_POST["user_name"]);
$u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$u_text = filter_var($_POST["user_text"]);
$error = array();
if (empty($u_date)){
$error['date'] = 'Date is empty!';
}
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
elseif (empty($u_name)){
echo "Name is empty.";
}
else{
require_once('db-connect.php');
$statement = $mysqli->prepare("INSERT INTO users_data (date, start_time, end_time, user_name, user_email, user_message) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssss', $u_date, $u_starttime, $u_endtime, $u_name, $u_email, $u_text);
if($statement->execute()){
print "Hello, " . $u_name . "!, request is complete!";
}else{
print $mysqli->error;
}
}
}
?>

You can add the 'required' attribute to <input> elements, which get validated on form submission. E.g. <input type="date" name="date" required/> eliminating the necessity to write code for error output.
EDIT: here you can see how the warning is shown
Also, the validation
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
is not required, since the user's choices already force starttime < endtime.
Cheers

Here is an example for setting date validation next to your date input fields.
in process.php:
` $errordate="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
if (empty($u_date)){
$errordate= 'Date is empty!';
}}
and in your index.php:
<input type="date" name="date"/> * <?php echo "<p style='color:red;'>".$errordate . "</p>"; ?>

Related

Edit functionality not works Php MySql

This is the code for edit.php where when I click edit this page opens and edits that specific line.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body><?php // if there are any errors, display them
if ($error != ''){echo '
<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label><br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" /><br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b><br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" /><br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" /><br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" /><br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" /><br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" /><br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" /><br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back();return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php } // connect to the database
include('connect.php');// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])){// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])){// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$telephone_number = mysql_real_escape_string(htmlspecialchars($_POST['telephone_number']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$job_title = mysql_real_escape_string(htmlspecialchars($_POST['job_title']));
$workplace = mysql_real_escape_string(htmlspecialchars($_POST['workplace']));
$country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$nationality = mysql_real_escape_string(htmlspecialchars($_POST['nationality']));// check that firstname/lastname fields are both filled in
if ($name == ''){// generate error message
$error = 'ERROR: Please fill in all required fields!';//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else{// save the data to the database
$link->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");// once saved, redirect back to the view page
header("Location: view.php");
}
}
else{// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else{ // if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){// query db
$id = $_GET['id'];
$result = $link->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);// check that the 'id' matches up with a row in the databse
if($row){// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];// show form //renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else{// if no match, display result
echo "No results!";
}
}
else{// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
It gives first warning that mysql is deprecated so I used below syntax but still it gives error:
mysqli_real_escape_string(htmlspecialchars($link,$_POST['name']));
Second major error its giving is that it takes me to this error message and makes all form fields empty. The line its showing always is:
ERROR: Please fill in all required fields!
Please Guide!
$servername = "localhost:3306";
$username = "root";
$password = "<Password here>";
$dbname = "TUTORIALS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tutorials_inf(name)VALUES ('".$_POST["name"]."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
I Solved My-Self...
Code Below...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<!--HTML form -->
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label>
<br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" />
<br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b>
<br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" />
<br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" />
<br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" />
<br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" />
<br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" />
<br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" />
<br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php
}
// connect to the database
$mysqli = new mysqli("sql213.byethost7.com", "b7_21234466", "mazhar2012", "b7_21234466_conference");
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = $mysqli->real_escape_string($_POST['name']);
//$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
//$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$telephone_number = $mysqli->real_escape_string($_POST['telephone_number']);
$email = $mysqli->real_escape_string($_POST['email']);
$job_title = $mysqli->real_escape_string($_POST['job_title']);
$workplace = $mysqli->real_escape_string($_POST['workplace']);
$country = $mysqli->real_escape_string($_POST['country']);
$nationality = $mysqli->real_escape_string($_POST['nationality']);
// check that firstname/lastname fields are both filled in
if ($name == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else
{
// save the data to the database
$mysqli->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = $mysqli->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];
// show form
//renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
$link->query($conn,"UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");

PHP to MYSQL form validation and database insertion with PHP_SELF and php process

I'm trying to use a php form saved on the artistRegister.php below and process it with the file at the bottom named processArtist.php .
I can't find the proper way to populate the fields in case there's an error and when I submit it to the database, I get an empty record on the database.
I'm populating a dropdown list on the navigation bar at header.php and using the same code to connect to the database, so it's not a database communication problem, since I'm able to create new empty records on the submit button press.
Tried several ways to make it work but would appreciate any help debugging the problem at hand.
Thank you advance.
***artistRegister.php***
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php if(isset($title)){ echo $title; }?></title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container-fluid">
<div class="col-xs-3">
</div>
<div class="col-xs-6">
<?php
// define variables and initialize with empty values
$artistName = $artistLabel = $websiteAddress = $facebookAddress = $youtubeAddress ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["artistName"])) {
$nameErr = "Enter Artist name";
}
else {
$artistName = $_POST["artistName"];
}
if (empty($_POST["artistLabel"])) {
$labelErr = "Enter Label name";
}
else {
$artistLabel = $_POST["artistLabel"];
}
}
?>
<form class="form" method="POST" action="processArtist.php">
<div class="form-group">
<label for="artistName">Artist Name:</label>
<input type="text" class="form-control" id="artistName" value="<?php echo htmlspecialchars($artistName);?>">
<span class="error" style="color: red"><?php echo $nameErr;?></span><br>
<label for="artistLabel">Artist Label:</label>
<input type="text" class="form-control" id="artistLabel" value="<?php echo htmlspecialchars($artistLabel);?>">
<span class="error"><?php echo $LabelErr;?></span><br>
<label for="websiteAddress">Artist Website:</label>
<input type="text" class="form-control" id="websiteAddress" value="<?php echo htmlspecialchars($websiteAddress);?>">
<label for="facebookAddress">Artist Facebook:</label>
<input type="text" class="form-control" id="facebookAddress" value="<?php echo htmlspecialchars($facebookAddress);?>">
<label for="youtubeAddress">Artist Youtube:</label>
<input type="text" class="form-control" id="youtubeAddress" value="<?php echo htmlspecialchars($youtubeAddress);?>">
<br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<div class="col-xs-3">
</div>
</div>
</body>
***processArtist.php***
<?php
$host="localhost";
$username="some_user_with_access";
$password="the_user_password";
$db_name="artist_management";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$artistName=$_POST['artistName'];
$artistLabel=$_POST['artistLabel'];
$websiteAddress=$_POST['websiteAddress'];
$facebookAddress=$_POST['facebookAddress'];
$youtubeAddress=$_POST['youtubeAddress'];
$sql="INSERT INTO artists (artistName, artistLabel, websiteAddress, facebookAddress, youtubeAddress)
VALUES
('$artistName', '$artistLabel', '$websiteAddress', '$facebookAddress', '$youtubeAddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

Updating post with PHP & MySQL

I'm building a sort of blog system, but I'm having trouble with editing an existing 'post' in the system. It is collecting the data from the database, and it displays it. But when I click the update button, I get this error. I've looked for it, checked my code couple of times, but I just couldn't find anything. This is the error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
And this is my code.
<?php //include config
require_once('../../includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bewerk</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="../style/normalize.css">
<link rel="stylesheet" href="../style/main.css">
<link rel="stylesheet" href="../style/login.css">
</head>
<body>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT patient_id, voornaam, achternaam, leeftijd, lengte, gewicht, foto_url FROM patienten WHERE patient_id = :patient_id') ;
$stmt->execute(array(':patient_id' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare('UPDATE patiënten SET patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
':patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
//redirect to index page
header('Location: index.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<div class="row">
<div class="col-md-2 col-md-offset-5">
<img src="../style/images/logo.png">
</div>
</div>
<div class="keuze_link row">
<p><b><?php echo $row['voornaam'];?> <?php echo $row['achternaam'];?></b> bewerken</p>
</div>
<div class="container">
<form class="toevoegen" action="" method="post">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];? >">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
</div>
</body>
</html>
If you guys wanna know more, or see more code, I'd like to hear it. Thanks in advance.
EDIT. for update.
//insert into database
$stmt = $db->prepare('UPDATE patienten SET patient_id = :patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
'patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
Latest form for update
<form class="toevoegen" action="" method="post">
<input type="hidden" name="voornaam" value="<?php echo $row['patient_id'];?>">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];?>">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
:patient_id is missing from the $stmt->execute() function. Please add it and try again.
In your update query you forgot about :patient_id to bind
And yes, remove $ before column names.

HTML form input for MySQL

I have a MySQL table named as letter and wish to insert records through the HTML data input form. Code as follows:
<head>
<meta charset="utf-8">
<link href="css/jquery-ui-1.10.1.css" rel="stylesheet">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui-1.10.1.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker(({ dateFormat: "yy-mm-dd" }));
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add Letter</title>
<style type="text/css" media="screen">
#import "style_contactform.css";
</style>
</head>
<?php
$querymethod = "select r_method_code, r_method from r_method order by r_method";
$resultmethod = mysql_query($querymethod) or die ( mysql_error());
$querybranch = "select bcode, branch from branch order by branch";
$resultbranch = mysql_query($querybranch) or die ( mysql_error());
$querytype = "select tcode, type from type order by type";
$resulttype = mysql_query($querytype) or die ( mysql_error());
?>
<?php
if (isset($_POST["submit"]))
{
$rno =$_POST["rno"];
$lno =$_POST["lno"];
$dol = mysql_real_escape_string($_POST["doi"]);
$hdg =$_POST["hdg"];
$from =$_POST["from"];
$address =$_POST["address"];
$method =$_POST["method"];
$type =$_POST["type"];
$branch =$_POST["branch"];
if ((empty($hdg))){
echo '<script language="javascript">';
echo 'alert("All fields must be required")';
echo '</script>';
}
else
{
$query ="INSERT INTO letter (reference_no, letter_no, date_stamp, heading, from_1, address, r_method_code, tcode, bcode) VALUES ('$rno', '$lno', '$dst', '$hdg', '$from', '$address', '$method', '$type', '$branch')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
echo '<script language="javascript">';
echo 'alert("Added Successfully")';
echo '</script>';
}
}
?>
<html>
<form id="contactform">
<div class="formcolumn">
<label for="rno">Reference No:</label>
<input type="text" name="rno" />
<label for="lno">Letter No:</label>
<input type="text" name="lno" />
<label for="dst">Date of the Letter:</label>
<input type="text" name="dst" id="datepicker" />
<label for="hdg">Heading:</label>
<textarea name="hdg"></textarea>
</div>
<div class="formcolumn">
<label for="from">From 1:</label>
<input type="text" id="from" />
<label for="address">Address:</label>
<textarea id="address"></textarea>
<label for="method">Received Method:</label>
<select name="method" span class="al">
<?php
do {
?>
<option value="<?php echo $rowmethod['r_method_code']?>"><?php echo $rowmethod['r_method']?></option>
<?php
} while ($rowmethod = mysql_fetch_assoc($resultmethod));
?>
</select>
<label for="type">Type:</label>
<select name="type" span class="al">
<?php
do {
?>
<option value="<?php echo $rowtype['tcode']?>"><?php echo $rowtype['type']?></option>
<?php
} while ($rowtype = mysql_fetch_assoc($resulttype));
?>
</select>
<label for="branch">Branch:</label>
<select name="branch" span class="al">
<?php
do {
?>
<option value="<?php echo $rowbranch['bcode']?>"><?php echo $rowbranch['branch']?></option>
<?php
} while ($rowbranch = mysql_fetch_assoc($resultbranch));
?>
</select>
</div>
<div class="buttons">
<input class="button" type="submit" value="Submit!" />
</div>
</form>
</html>
But I was unable to add records through this form to the relevant table. I can not understand what I am going wrong. Can any one help me?... Pls...
Form's Attribute method's default value is get
You should specify it like this
<form id="contactform" method="post">
Now you can use $_POST to get data!

SESSION variable value is not passing

I'm trying to pass a value from a select input control on an HTML form.
When I hardcode it, it gets echoed, when not, all I get is this:
The invention type did not go through correctly.
Here is my page1.php:
<?php
session_start();
$_SESSION['invtype'] = $invtype;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if (!$errors) {header("location: offerform_switch.php");
}
else {
echo '<div style="color: red">' . $errors . '<br/>
</div>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Offer Form, Part 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="inventron_sage_short.css" type="text/css" />
<link rel="stylesheet" href="form.css" type="text/css" />
</head>
<body>
<div id = "logo">
<img src = "img/top.jpg" alt = "logo" />
</div>
<div id = "wrapper">
<div id="stylized" class="myform">
<form id="form" action="page1.php" method="post">
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<div id = "category">Categorize your invention:</div>
<div class="spacer"></div>
<p>
<select id="invtype" name="invtype">
<option value="0" selected="selected">Select type</option>
<option value="product">PRODUCT</option>
<option value="software">SOFTWARE</option>
</select>
<input type="submit" name="Submit" value="Next!" />
</div>
</div>
</body>
</html>
Here is my offerform_switch.php:
<?php
session_start();
// echo variable from the session, we set this on our other page
echo $_SESSION['invtype'];
$invtype = $_SESSION['invtype'];
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("mysql.myserver.com","myuser","mypassword"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("invention") or die("Unable to select database"); //select which database we're using
switch ($invtype){
case "product":
include("page2_product.php");
break;
case "software":
include("page2_software.php");
break;
default:
echo "The invention type did not go through correctly.";
}
?>
What am I doing wrong?
Thank you!
It should be
$_SESSION['invtype'] = $_POST['invtype'];
You're missing "session_id();" right below the "session_start();". I don't know why exactly it's required, but if I remember correctly, it is.

Categories