Empty SQL after form submission - php

I've searched and searched I cannot find an answer to this
I've made a form HERE It's very basic. Somehow it's not submitting the final data. the code is
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit"></p>
</form>
That's the form
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tournament1 (team, teammates, cap, email, subs)
VALUES ('$_POST[team]','$_POST[cap]','$_POST[email]','$_POST[teammates]','$_POST[subs]')";
if ($conn->query($sql) === TRUE) {
echo "Your team has been submitted Thankyou. You will be redirected back to the tournaments page Shortly";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
What am I doing wrong? It will connect and do something because the ID fills because of its autoincremented. everything else gets lost.
Thanks in advance guys
Kyle

So I switched it around a little for you but this should work fine..
firstly the form, I have added an isset in for you:
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit" name="sendit"></p>
</form>
You'll notice I have changed action to action="" so it runs under its own page.
Followed next by the PHP of which I have added conditions into for you.
Add the PHP to submit.php
Please note: you can also add required at the end of each input field.
if (isset($_POST['sendit']))
{
$team = $_POST['team'];
$captain = $_POST['cap'];
$email = $_POST['email'];
$mates = $_POST['teammates'];
$sub = $_POST['subs'];
if (!empty($team))
{
if (!empty($captain))
{
if (!empty($email))
{
if (!empty($mates))
{
if (!empty($sub))
{
$sql = "INSERT INTO `tournament1` (team, teammates, cap, email, subs) VALUES ('$team', '$mates', '$captain', '$email', '$sub')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Please add subs..";
}
} else {
echo "Please add mates..";
}
} else {
echo "Please add captains email..";
}
} else {
echo "Please add captains name..";
}
} else {
echo "Please add team name..";
}
}

Related

PHP form submission for multiple entry

How can I keep the current form with clear fields after successful insertion. I have used to php files, one for connecting the database and another for collecting data from user. Both of the files code are given below:
For connecting database:
<?php
$servername = "localhost";
$username = "local";
$password = "host";
$dbname = "form";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}
$roll=$_POST['roll'];
$name=$_POST['name'];
$city=$_POST['city'];
$sql = "insert into people_info (roll,name,city) values ('$roll','$name','$city')";
if(mysqli_query($conn,$sql)){
echo "New record created successflly";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
mysqli_close($conn);
?>
And the form page is:
<html>
<body>
<form action="connection.php" method="post">
<table border="1">
<tr>
<th>
Field
</th>
<th>
Value
</th>
</tr>
<tr>
<td>
Roll:
</td>
<td>
<input type="text" name="roll"/><br>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name"/><br>
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<input type="text" name="city"/><br>
</td>
</tr>
<tr>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Instead of this:
if(mysqli_query($conn,$sql)){
echo "New record created successfully";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
try
if(mysqli_query($conn,$sql)){
header('location: page1.php?message=New record created successfully');
}
else{
header('location: page1.php?message=' . mysqli_error($conn));
}
here header() function will redirect you to form page with $message variable having response message. Use it to show the response on page.

my INSERT INTO is not working in PHP page but working in SQL

i have here a page for the registering a crew but i dont know what seems to be the problem. the query is working in phpmyadmin but not working in php page.
here is my code:
session_start();
require 'config.php';
if (#$_SESSION['username']) {
if (isset($_POST['first_name'])&&isset($_POST['middle_name'])&&isset($_POST['last_name'])&&isset($_POST['age'])&&isset($_POST['birth_date'])&&isset($_POST['birth_place'])&&isset($_POST['gender'])&&isset($_POST['martial_status'])&&isset($_POST['religion'])&&isset($_POST['nationality'])&&isset($_POST['email'])&&isset($_POST['address1'])&&isset($_POST['address2'])&&isset($_POST['course'])&&isset($_POST['school'])&&isset($_POST['remarks'])) {
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$age = $_POST['age'];
$birth_date = $_POST['birth_date'];
$birth_place =$_POST['birth_place'];
$gender = $_POST['gender'];
$martial_status = $_POST['martial_status'];
$religion = $_POST['religion'];
$nationality = $_POST['nationality'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$course = $_POST['course'];
$school = $_POST['school'];
$remarks = $_POST['remarks'];
$date_added = date('Y-m-d');
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else {
echo 'Some field is empty';
}
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Add New Crew</title>
</head>
<body>
<form action="add_crew.php" method="POST">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="first_name" ></input>
</td>
</tr>
<tr>
<td>
Middle Name:
</td>
<td>
<input type="text" name="middle_name" ></input>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="last_name" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Age:
</td>
<td>
<input type="text" name="age" ></input>
</td>
</tr>
<tr>
<td>
Birth Date:
</td>
<td>
<input type="text" name="birth_date" ></input>
</td>
</tr>
<tr>
<td>
Birth Place:
</td>
<td>
<input type="text" name="birth_place" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Gender:
</td>
<td>
<input type="text" name="gender" ></input>
</td>
</tr>
<tr>
<td>
Martial Status:
</td>
<td>
<input type="text" name="martial_status" ></input>
</td>
</tr>
<tr>
<td>
Religion:
</td>
<td>
<input type="text" name="religion" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Nationality:
</td>
<td>
<input type="text" name="nationality" ></input>
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<input type="text" name="email" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Address 1:
</td>
<td>
<input type="text" name="address1" ></input>
</td>
</tr>
<tr>
<td>
Address 2:
</td>
<td>
<input type="text" name="address2"></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Course:
</td>
<td>
<input type="text" name="course" ></input>
</td>
</tr>
<tr>
<td>
School Graduated:
</td>
<td>
<input type="text" name="school" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Remarks:
</td>
<td>
<input type="text" name="remarks"></input>
</td>
</tr>
</table><br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>';
}
else { header('Location: /practice1/index.php');
}
?>
this is the entire page of php
Just like Saty say you forget to insert query
$conn->query($query); // PDO for new php7
mysql_query($query,$conn); // for old code but this is deprecated
//$conn is mysql_connect in config.php (it's may be in another variable up on your write)
<?php if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status)
VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
// for mysqli code starts
mysqli_query($con, $query);
// for mysqli code ends where $con is connection variable
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
?>
you have to fire the query to insert in database , i think you forgot
add this code after your query to execute it
if (mysqli_query($conn,$query)) {
echo 'Your request is sent to queue';
}
else {
echo 'Something went wrong';
}
I think you missed Two points
1.connection between your php and mysql.
2.Firing the query.
Try with this snippet.
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$conn = mysql_connect($dbhost, $username, $password);
//connection to the database
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
and then put
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
After that fire your query
if (mysqli_query($conn,$query))
{
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else
{
echo 'Some Syntax is wrong';
}
}
else {
echo 'Some field is empty';
}
And close the connection after used by
mysql_close($conn);
#prakash above is the closest to correct...
however, i think, set all of your inputs on your html with value="", so that you do not have to do all of the if(!empty() garbage and get blanks later...
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$dbname = "your_db";
// just good practice to specify the db, later you may have multiple on the same server..
// use mysqli as someone else above stated...
$conn = mysqli_connect($dbhost, $username, $password,$dbname);
if(!$conn){
die('Connect Error: ' . mysqli_connect_error());
//again.. mysqli.. not mysql
}
// dont kill yourself with manual entry errors for the query...
// move $_POST to a new variable and prep the array for a loop;
$data = $_POST;
// get rid of the submit variable
unset($data['submit']);
// assuming this db field is int not varchar
// and assuming birthdate field is DATE or varchar
$data['age'] = intval($data['age']);
$data['birthdate'] = date('Y-m-d',strtotime($date['birthdate']));
// would be easier to set default value NOW() for date_added column and DATETIME
// NOW() will set that field to the CURRENT_TIMESTAMP on every insert for you...
// but the way you have it, and assuming db field is DATE or varchar
$data['date_added'] = date('Y-m-d');
// Same for 'crew_status' .. field VARCHAR or ENUM... default value 'PENDING'
$data['crew_status'] = 'PENDING';
// make a string variable to fill with fields...
$fields = '';
// make a string variable to to fill with insert values....
$values = '';
// loop through $data, add each value followed by a comma to string
// no single quotes on integers where the db field is INT .... like age...
foreach($data as $key=>$val){
// this is looking for the value="" from when a user blanks an input field....
if($val == ''){
// handles blank user inputs.. db fields NOT set 'not null'..no quotes around NULL
$values .= 'NULL,';
// if the value is not blanked... look for strings and dates....
}elseif(!is_int($val)){
// real_escape_string will kill any characters that will error like ' or \
// and remove in sql injection risks .. single quotes on varchar db field vals
$values .="'".mysqli_real_escape_string($conn,$val)."',";
// if input is not blank and !is_int() must be INT...age
}else{
//no quotes on integers going into INT db fields....
$values .= $val.',';
}
// add the $key (field name) to the $fields same order as $values, comma after each
// backticks around field names...
$fields .= "`".$key."`,";
}
// we are dragging an extra comma on $fields and $values at the end of each string
// we will get them in the insert query string....splitting up the query to explain
$query = "INSERT INTO `crew_info`";
//substr off the comma $fields is dragging "," put it between ( and )
$query .= "(".substr($fields,0,-1).")";
//substr off the comma $values dragging "," put it between ( and )
$query .= " VALUES (".substr($values,0,-1).")";
//not split query might be confusing to read..query would look like...
//"INSERT INTO `crew_info`(".substr($fields,0,-1).") VALUES (".substr($values,0,-1).")"
//now insert
if(!mysqli_query($conn,$query)){
// if there is an error... let someone know!
die('ooops!...'.mysqli_error());
}else{
// if no error......
echo 'you just inserted data!!! id# = '. mysqli_insert_id($conn);
}
There is an error in your sql string. INSERT INTO table VALUES(..,..);
$query = "INSERT INTO `crew_info` VALUES (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";

Adding Data to mySql

I have a form and trying to insert data to the mysql database. but it always jump into the error.
Same database connection working fine to view data already in the database.
Database Connection for the page stored in a separate file :
<?php
$host ="localhost";
$user = "CENSORED";
$password = "CENSORED";
$link = mysql_connect($host,$user,$password) or die("An error occurred while connecting...");
//Database Selection
$dbname="CENSORED";
mysql_select_db($dbname);
?>
HTML Form
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP Code
<?php
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>
Thanks in advance.
you have to include your Database connection file which you have kept as separate file in your php file.
<?php
include("dbconnection filename.php"):// this line.
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>
Change to this
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('".$admin_email."','".$admin_name."','".$admin_mobile."','".$admin_address."','".$admin_password."')";
use mysql_real_escape_string
$admin_email=mysql_real_escape_string($_POST['admin_email']);
$admin_name=mysql_real_escape_string($_POST['admin_name']);
$admin_mobile=mysql_real_escape_string($_POST['admin_mobile']);
$admin_address=mysql_real_escape_string($_POST['admin_address']);
$admin_password=mysql_real_escape_string($_POST['admin_password']);
You have problems with connecting to a database. I don't like your approach to of connecting to a database so i'll provide mine approach (which works so far).
Your database config should look like
class DataBaseClass{
public $_host = "localhost";
public $_user = "X32284679";
public $_database = "X32284679";
public $_pass = "X32284679";
function connectToDatabase(){
$conn = new mysqli($this->_host, $this->_user, $this->_pass, $this->_database);
$conn->set_charset("utf8");
return $conn;
if(! $conn) {
echo "Problems with connecting to database!";
exit;
}
}
}
Later on in some other code you use this file like this
require('nameOfFile.php');
$db = new DataBaseClass();
$mysqli=$db->connectToDatabase();
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if($rs = $mysqli->query($sql)) {
//inserted
else {
//not inserted
$mysqli->close();
}
And so on, try this approach and see if it helps you.
In your PHP page you should include your connection file:
require_once('yourdbconnection.php');
And change $_POST['admin_password'] to $_POST['admin_pw'] according to your HTML.
HTML
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP
<?php
require_once('yourdbconnection.php');
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_pw'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
mysqli_query($link, $sql) or die("Error: " . mysqli_error($link));
mysqli_close($link);
?>
This works for me. If it doesn't for you then:
Check if query columns match table columns
Check if you are using the right database and the right table
Check if you are checking result on the right database and the right table
Hope this helps!
EDIT
NOTE: I highly suggest you to switch from mysql to mysqli since mysql is now deprecated.
As you asked me to help out in one of my previous answers i decided to do some fancy stuff with this code :)
Remember, the db rows need to be named the same as your form name="name" for this to work!
db_connect.php:
$dbhost = ""; // this will ususally be 'localhost', but can sometimes differ
$dbname = ""; // the name of the database that you are going to use for this project
$dbuser = ""; // the username that you created, or were given, to access your database
$dbpass = ""; // the password that you created, or were given, to access your database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('An error occured while connecting to: '. $dbhost.' as: '.$dbuser);
mysql_select_db($dbname, $conn) or die('Sorry, an error occured when selecting the database: '.$dbname);
form.php:
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
add_admin.php:
include 'db_connect.php'; //include connection
//Why add all post thingys when you can do it dynamically ?
$i = count($_POST);
$e = 0;
//Do a foreach loop on all POSTS coming in to this file..
foreach($_POST as $Key => $Value){
//Add commas behind everything :)
if($e++ < $i - 1){
//Escaping all the strings:
$Rows .= mysql_real_escape_string($Key).", ";
$Values .= "'".mysql_real_escape_string($Value)."', ";
}
//if its the last one, dont add a comma behind!
else{
//Still escaping all the strings:
$Rows .= mysql_real_escape_string($Key);
$Values .= "'".mysql_real_escape_string($Value)."'";
}
}//end foreach loop
//Insert etc etc...
$sql = mysql_query("INSERT INTO admin($Rows) VALUES($Values)");
//If successful:
if(mysql_query($conn, $sql)){
echo "Records added.";
}
//Error ?
else{
echo "Sorry, an error occured while inserting to: ".$Rows;
echo "<br/>";
mysql_error($conn);
}
//Close connection:
mysql_close($conn);

Undefined index:firstname,lastname,email,phone in line83

I am having problem in this following code.It says undefined index on line 83.The second problem is that there is a huge gap between the text fill the required form and the input textbox of the form during output.Please help me out.The code is posted below.
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$firstnameErr = $lastnameErr = $emailErr = "";
$firstname = $lastname = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["firstname"]))
{
$firstnameErr = "Name is required";
}
else
{
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"]))
{
$lastnameErr = "Name is required";
}
else
{
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text align =center><h1>Eventous Info</h1></div>
<h3>Fill the Required Form:</h3>
<p><span class="error">*required field</span></p>
<table>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<tr><?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span></td><br><br>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><td><br><br>
</tr>
</table>
<input type="submit" >
</form>
<?php
$con = mysql_connect("localhost","ashu123","bangalore");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("evantus", $con);
$sql="INSERT INTO employee (firstname, lastname, email, phone )
***LINE-83***
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]','$_POST[number]')";
$sql = "select * from employee";
$query = mysql_query( $sql );
echo "<table>";
echo "<tr><th>firstname</th>";
echo "<th>lastname</th>";
echo "<th>email</th>";
echo "<th>phone</th></tr>";
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td>$row[firstname]</td>";
echo "<td>$row[lastname]</td>";
echo "<td>$row[email]</td>";
echo "<td>$row[phone]</td></tr>";
}
echo "</table>";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
</body>
</html>
Your form has invalid html code. In short, just use:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><br /><br /><td>
<td></td>
</tr>
</table>
<input type="submit" >
</form>
More about it:
1. After opening the <table> element, next one must be table row, so <form> must be a wrapper to your table.
2. You have placed breaks after closing the </td> tag, which is wrong - they should be inside table cell.
3. Ref: undefined index, guess it is only a warning that you are using the $_POST variable that does not exist.
I feel your insert query is not right, try the query below.
$sql="INSERT INTO employee (firstname, lastname, email, phone ) VALUES ('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['email']."','".$_POST['number']."')";

Get post value from a select tag PHP

Hey I need to get the gender selected from a select tag
and then store that value as a variable in php, here's some relevant snippets of both
the register.php form and the register_process.php file
register.php
<form action="register_process.php" method="post">
<table>
<tr>
<td>Username (to be used for login and display name)</td>
<td><input type="text" name="username" id="username" onclick="check()"/></td>
<td id="username_check"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" onclick="check()"/></td>
<td id="password_check"></td>
</tr>
<tr>
<td>Password (Re-Enter)</td>
<td><input type="password" name="repassword" id="repassword" onclick="check()"/></td>
<td id="repassword_check"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email" id="email" onclick="check()"/></td>
<td id="email_check"></td>
</tr>
<tr>
<td>Email Address (Re-Enter)</td>
<td><input type="text" name="reemail" id="reemail" onclick="check()"/></td>
<td id="reemail_check"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>I agree to the terms and conditions</td>
<td><input type="checkbox" name="tos" id="tos" /></td>
<td id="tos_check"></td>
</tr>
<tr>
<td id="valid" colspan="3"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Register" /></td>
</tr>
<tr>
<td colspan="3">Cancel</td>
</tr>
</table>
</form>
there is a ton of javascript I have omitted from this that does very basic validation
register_process.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
?>
<?php
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DATABASE, $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$repassword = mysql_real_escape_string($_POST['repassword']);
$email = mysql_real_escape_string($_POST['email']);
$reemail = mysql_real_escape_string($_POST['reemail']);
$gender = $_POST['gender'];
$tos = mysql_real_escape_string($_POST['tos']); // not being checked yet
$errors = 0;
$success = 0;
// USERNAME CHECK
if (preg_match('/^[a-z\d_]{5,20}$/i', $username))
{
$user_query = "SELECT * FROM users WHERE user_name = '$username' OR login_name = '$username' LIMIT 1";
$result=mysql_query($user_query);
$count=mysql_num_rows($result);
if($count==0)
{
echo "username is available <br/>";
$success++;
echo "<br/>1 Passed<br/>";
}
else
{
echo "sorry, that username already exist";
$errors++;
echo "<br/>1 Passed<br/>";
}
}
else
{
echo "You either need to enter a username, or you have entered a username in an incorrect format.";
$errors++;
echo "<br/>1 Passed<br/>";
}
// PASSWORD CHECK
if(preg_match('/^[a-z\d_]{5,20}$/i', $password))
{
// password is between 5-10 characters, alpha-numeric (a-z, A-Z, 0-9) and underscores
if($password === $repassword)
{
// password is identical
$success++;
echo "<br/>2 Passed<br/>";
}
else
{
// passwords do not match
$errors++;
echo "<br/>2 Passed<br/>";
}
}
else
{
echo "Password failed validation";
$errors++;
}
// EMAIL CHECK
if (eregi('^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$',$email))
{
// user#email.com passes
// 1#1.com passes
// -#_.com passes
//
echo "<br/> email is ok";
if($email === $reemail)
{
// email addresses match
$success++;
echo "<br/>3 Passed<br/>";
}
else
{
// email address does not match
echo "<br/>3 Passed<br/>";
$errors++;
}
}
else
{
echo "email validation failed <br/>";
$errors++;
echo $email;
}
// Here is the problem, I can't seem to evaluate the correct value,
// When I echo out $gender I get nothing, So theres either an issue
// in the html form OR in the way I use $gender = $_POST['gender'];
if($gender == 1 || $gender == "1" || $gender == '1')
{
echo "male selected";
}
else
{
echo "female selected";
}
?>
what am I missing here guys?,
I have been hunting around
google to find an answer with no success.
heres the error php is giving me:
"Notice: Undefined index: gender in register_process.php on line 22"
Everything else in the form IS working fine, there are no other issues
Your mistake is this:
/>
Don't close your form tag way up there - you need to close it after the select.
BTW xhtml is dead, don't use it (it has been superseded by html5). Use plain HTML and don't close tags that don't need it.
Because of error in your HTML syntax.
Change:
<form action="register_process.php" method="post" />
To:
<form action="register_process.php" method="post">

Categories