Solved

PHP check that form value is not blank

Posted on 2011-03-04
17
301 Views
Last Modified: 2012-05-11
Hi Experts,

I have the following attached code, it already checks for malicious characters but whats the easiest way to check that a field has not been left blank and if so to identify the field to the user?

Many Thanks,
Dean.
if(!empty($_POST) && isset($_POST))
{
	//make variables safe to insert
  $id = mysql_real_escape_string($_POST['id']);
  $Forename = mysql_real_escape_string($_POST['Forename']);
	$Surname = mysql_real_escape_string($_POST['Surname']);
	$Arrival_Date = mysql_real_escape_string($_POST['Arrival_Date']);
	$Departure_Date = mysql_real_escape_string($_POST['Departure_Date']);
	$RoomNo = mysql_real_escape_string($_POST['RoomNo']);
	$Tel = mysql_real_escape_string($_POST['Tel']);

	//query to insert data into table
	$sql = "
		INSERT INTO bookings
		SET
		id = '$id',
		Forename = '$Forename',
		Surname = '$Surname',
		Arrival_Date = '$Arrival_Date',
		Departure_Date = '$Departure_Date',
		RoomNo = '$RoomNo',
		Tel = '$Tel'";
	$result = mysql_query($sql);
	if(!$result)
	{
		echo "Failed to insert record<br>Please Ensure booking does not currently exist";
	}
	else
	{
		echo "Record inserted successfully";
	}
}
?>

Open in new window

0
Comment
Question by:deanlee17
  • 9
  • 8
17 Comments
 

Author Comment

by:deanlee17
Comment Utility
Below is an attempt, but if ID and Forename are both empty then the echo only says "Please insert ID." I want it to flag up all missing fields.
if(!$id)
	{
		echo "Please insert ID<br>";
	}
	elseif(!$Forename)
	{
		echo "Please Enter Forename<br>";
	}
	else
	{
		
	
	// end test
	
	//query to insert data into table
	$sql = "
		INSERT INTO bookings
		SET
		id = '$id',
		Forename = '$Forename',
		Surname = '$Surname',
		Arrival_Date = '$Arrival_Date',
		Departure_Date = '$Departure_Date',
		RoomNo = '$RoomNo',
		Tel = '$Tel'";
	$result = mysql_query($sql);
	if(!$result)
	{
		echo "Failed to insert record<br>Please Ensure booking does not currently exist";
	}
	else
	{
		echo "Record inserted successfully";
	}
}
}

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
You can try
if(!$id){echo "Please insert ID<br>";}
if(!$Forename){echo "Please Enter Forename<br>";}
and so on (not using elseif but simple if)
0
 

Author Comment

by:deanlee17
Comment Utility
Hi Roads,

That seems to work for the error message. Is there any better way to loop through the vaiables rather than just having....

if(!$id)
 {
    echo "Please insert ID<br>";
 }
if(!$Forename)
 {
    echo "Please Enter Forename<br>";
  }

etc etc

Thanks,
Dean.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
A simple example:
<?php
    if(!empty($_POST)){
        foreach($_POST as $key => $val){
            if(empty($_POST[$key])) echo"Please insert $key<br />";
        }
    }
?>

<form action="#" method="post">
    <input type="text" name="var1" /> var1<br />
    <input type="text" name="var2" /> var2<br />
    <input type="text" name="var3" /> var3<br />
    <input type="submit" value="send" />
</form>

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
Oh, allright then :) This would the code look like I guess (not tested)

<?php

if(!empty($_POST) && isset($_POST))
{

    if(!empty($_POST)){
        foreach($_POST as $key => $val){
            if(empty($_POST[$key])) echo"Please insert $key<br />";
        }
    }else{

        //make variables safe to insert
      $id = mysql_real_escape_string($_POST['id']);
      $Forename = mysql_real_escape_string($_POST['Forename']);
        $Surname = mysql_real_escape_string($_POST['Surname']);
        $Arrival_Date = mysql_real_escape_string($_POST['Arrival_Date']);
        $Departure_Date = mysql_real_escape_string($_POST['Departure_Date']);
        $RoomNo = mysql_real_escape_string($_POST['RoomNo']);
        $Tel = mysql_real_escape_string($_POST['Tel']);

        //query to insert data into table
        $sql = "
            INSERT INTO bookings
            SET
            id = '$id',
            Forename = '$Forename',
            Surname = '$Surname',
            Arrival_Date = '$Arrival_Date',
            Departure_Date = '$Departure_Date',
            RoomNo = '$RoomNo',
            Tel = '$Tel'";
        $result = mysql_query($sql);
        if(!$result)
        {
            echo "Failed to insert record<br>Please Ensure booking does not currently exist";
        }
        else
        {
            echo "Record inserted successfully";
        }
    }
}


?>

Open in new window


0
 

Author Comment

by:deanlee17
Comment Utility
haha thanks roads. Would that display all empty fields?
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
Yes, it should - test it.
0
 

Author Comment

by:deanlee17
Comment Utility
Hmm error checking is working well. But it now wont insert a genuine record.

See code attached.

Thanks for your help so far
<?


$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

//NOTE: MAKE SURE YOU DO YOUR OWN APPROPRIATE SERVERSIDE ERROR CHECKING HERE!!!
if(!empty($_POST) && isset($_POST))
{

    if(!empty($_POST)){
        foreach($_POST as $key => $val){
            if(empty($_POST[$key])) echo"Please insert $key<br />";
        }
    }else{

        //make variables safe to insert
      $id = mysql_real_escape_string($_POST['id']);
      $Forename = mysql_real_escape_string($_POST['Forename']);
        $Surname = mysql_real_escape_string($_POST['Surname']);
        $Arrival_Date = mysql_real_escape_string($_POST['Arrival_Date']);
        $Departure_Date = mysql_real_escape_string($_POST['Departure_Date']);
        $RoomNo = mysql_real_escape_string($_POST['RoomNo']);
        $Tel = mysql_real_escape_string($_POST['Tel']);

        //query to insert data into table
        $sql = "
            INSERT INTO bookings
            SET
            id = '$id',
            Forename = '$Forename',
            Surname = '$Surname',
            Arrival_Date = '$Arrival_Date',
            Departure_Date = '$Departure_Date',
            RoomNo = '$RoomNo',
            Tel = '$Tel'";
        $result = mysql_query($sql);
        if(!$result)
        {
            echo "Failed to insert record<br>Please Ensure booking does not currently exist";
        }
        else
        {
            echo "Record inserted successfully";
        }
    }
}



?>

<table width="300" border="1">
	<tr>
		<td><b>ID</b></td>
		<td><b>Forename</b></td>
		<td><b>Surname</b></td>
		<td><b>Arrival_Date</b></td>
		<td><b>Departure_Date</b></td>
		<td><b>RoomNo</b></td>
		<td><b>Tel</b></td>
	</tr>
	<?
	//show data from tables
	$sql = "
		SELECT *
		FROM bookings
		ORDER BY ID ASC
		LIMIT 20";
	$result = mysql_query($sql);
	while($row = mysql_fetch_array($result))
	{
	//print data
	?>
	<tr>
		<td><? echo $row['id']; ?></td>
		<td><? echo $row['Forename']; ?></td>
		<td><? echo $row['Surname']; ?></td>
		<td><? echo $row['Arrival_Date']; ?></td>
		<td><? echo $row['Departure_Date']; ?></td>
		<td><? echo $row['RoomNo']; ?></td>
		<td><? echo $row['Tel']; ?></td>
	</tr>
	<?
	}
	?>
</table>

Open in new window

0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 27

Accepted Solution

by:
Lukasz Chmielewski earned 500 total points
Comment Utility
Yes, that's right, my bad

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

//NOTE: MAKE SURE YOU DO YOUR OWN APPROPRIATE SERVERSIDE ERROR CHECKING HERE!!!
if(!empty($_POST) && isset($_POST))
{
    $emptyvariables = false;

    if(!empty($_POST)){
        foreach($_POST as $key => $val){
            if(empty($_POST[$key])){
                echo"Please insert $key<br />";
                $emptyvariables = true;
                }
        }
    }
    
    if($emptyvariables == false){
    


        //make variables safe to insert
      $id = mysql_real_escape_string($_POST['id']);
      $Forename = mysql_real_escape_string($_POST['Forename']);
        $Surname = mysql_real_escape_string($_POST['Surname']);
        $Arrival_Date = mysql_real_escape_string($_POST['Arrival_Date']);
        $Departure_Date = mysql_real_escape_string($_POST['Departure_Date']);
        $RoomNo = mysql_real_escape_string($_POST['RoomNo']);
        $Tel = mysql_real_escape_string($_POST['Tel']);

        //query to insert data into table
        $sql = "
            INSERT INTO bookings
            SET
            id = '$id',
            Forename = '$Forename',
            Surname = '$Surname',
            Arrival_Date = '$Arrival_Date',
            Departure_Date = '$Departure_Date',
            RoomNo = '$RoomNo',
            Tel = '$Tel'";
            
            echo"$query";
        $result = mysql_query($sql);
        if(!$result)
        {
            echo "Failed to insert record<br>Please Ensure booking does not currently exist";
        }
        else
        {
            echo "Record inserted successfully";
        }
    }
}



?>

<table width="300" border="1">
	<tr>
		<td><b>ID</b></td>
		<td><b>Forename</b></td>
		<td><b>Surname</b></td>
		<td><b>Arrival_Date</b></td>
		<td><b>Departure_Date</b></td>
		<td><b>RoomNo</b></td>
		<td><b>Tel</b></td>
	</tr>
	<?
	//show data from tables
	$sql = "
		SELECT *
		FROM bookings
		ORDER BY ID ASC
		LIMIT 20";
	$result = mysql_query($sql);
	while($row = mysql_fetch_array($result))
	{
	//print data
	?>
	<tr>
		<td><? echo $row['id']; ?></td>
		<td><? echo $row['Forename']; ?></td>
		<td><? echo $row['Surname']; ?></td>
		<td><? echo $row['Arrival_Date']; ?></td>
		<td><? echo $row['Departure_Date']; ?></td>
		<td><? echo $row['RoomNo']; ?></td>
		<td><? echo $row['Tel']; ?></td>
	</tr>
	<?
	}
	?>
</table>

Open in new window

0
 

Author Comment

by:deanlee17
Comment Utility
Ok, it now trys to insert but fails everytime, we hit the echo "Failed to insert record<br>Please Ensure booking does not currently exist";

Many Thanks :)
0
 

Author Comment

by:deanlee17
Comment Utility
0
 

Author Comment

by:deanlee17
Comment Utility
Nope ignore that! It works.

Could you just describe how these 2 lines work and then we are done :)

  foreach($_POST as $key => $val){
            if(empty($_POST[$key])){
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
Is there any identity column in the database ? Isn't id a primary unique key ?
0
 

Author Comment

by:deanlee17
Comment Utility
See my post above :)
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
:)
POST is an array of key -> value, key is the name of the input field, value is its value, you can see it clearly, when you put print_r($_POST); just before that:

  foreach($_POST as $key => $val){
            if(empty($_POST[$key])){
0
 

Author Comment

by:deanlee17
Comment Utility
Excellent. Thanks for all the help.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
No problem
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now