how to show error message if someone left a field blank - php

So I created this page where a user can send data to a msql database but when they leave a field blank and they click submit I want an error to show up saying "You left a field blank".
This is the code:
<?php
$hostname = "";
$db_user = "";
$db_password = "";
$database = "";
$db_table = "";
# STOP HERE
####################################################################
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
?>
<html>
<head>
<title>Add your url to out database</title>
</head>
<body>
<?php
if (isset($_REQUEST['Submit'])) {
# THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
$sql = "INSERT INTO $db_table(title,description,url,keywords) values ('".mysql_real_escape_string(stripslashes($_REQUEST['title']))."','".mysql_real_escape_string(stripslashes($_REQUEST['description']))."','".mysql_real_escape_string(stripslashes($_REQUEST['url']))."','".mysql_real_escape_string(stripslashes($_REQUEST['keywords']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into our database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1><center><img src='addalink.png'><center></h1>
<hr>
<center>
<form method="post" action="">
Name of the song:<br>
<input type="text" name="title"><br>
Artist: <br>
<input type="text" name="description"><br>
Download link: <br>
<font color="#0000FF">http://</font><input type="text" name="url"><br>
<input type="submit" name="Submit" value="Submit">
</form></br>
<?php
}
?> <center>
</body>
</html>

First of all, use a CSS style to style your form's inputs. It's a lot easier to read, and it means if you need to change anything in the future it's quick.
What you're wanting to do is run a script on submit that checks whether or not the values in the required fields are what you expect.
The jQuery Validation Plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ takes care of what you want.
If you want to write your own, it's a process of attaching the validation function to the click event of the submit button (or the onSubmit event of the form) and checking the data that's in the form.
If the data is missing, you add a class to show this. If the data is valid, you remove the previous class.
Finally, you only return true (to submit the form) in the case everything validates.
Keep in mind this is only client side, you still need to validate your data server side for security.

So, the common response is "do this on the front-end". If anything you are posting has security implications then I'd also recommend you check your form data on the back-end.
Also if you're going to go through the process of using mysql_real_escape, you might as well use mysqli and parameterized queries see: http://us2.php.net/manual/en/mysqli-stmt.prepare.php.
If you choose to go the back-end route, especially if you are using AJAX for the post, you can throw an Exception that actually outputs a 500 error along with the message you want to display, and then use Javascript to handle the "error case", so you can provide really nice validation methods that still do the validation on the server side.

Related

Can't use function return value

I'm new to PHP and developing a login form. Please find below the code I used. When I tried it gave me the following error:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
Please help me to fix the issue.
Source code for thems/login.html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action=".\login.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" id="Submit_button">
</form>
</body>
</html>
Source code for index.php:
<?php
// venushka thisara dharmasiri
require 'config.php';
require 'thems\login.html';
?>
Source code for login.php:
<?php
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
?>
Source code for config.php:
<?php
$dbUser="root";
$dbPassword="";
$dbName="forsitelogin";
$dbHost="localHost";
$dbConnection= mysql_connect($dbHost, $dbUser, $dbPassword);
if($dbConnection)
{
mysql_select_db($dbName);
//print("Sucessfully connected to database");
}
else
die("<strong>Cound not connect to database </strong> ");
?>
Should be $_POST["Submit_button"] instead of $_POST("Submit_button")
The error the script returns explains it:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
If you don’t understand the meaning of the error—and believe me, most error messages are bizarre even to experienced programmers—look at the line number referenced. And looking at line 3 in login.php shows me the error; $_POST("Submit_button") is invalid:
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
It should be $_POST["Submit_button"]:
if(isset($_POST["Submit_button"])==true)
print("Submit button pressed");
else
print("submit button sorry");
But looking at it further, why is there an ==true? It can simply be like this:
if(isset($_POST["Submit_button"]))
print("Submit button pressed");
else
print("submit button sorry");
But I would recommend doing a better check on that value like this:
if(array_key_exists("Submit_button", $_POST) && !empty(trim($_POST["Submit_button"])))
print("Submit button pressed");
else
print("submit button sorry");
I find that using array_key_exists and a combination of !empty with trim works better for basic user submitted data verification.
First some code clean up might help. PHP does not require braces in if() else syntax; however, a great place to start. I would suggest diving into basic syntax of PHP here. Not that what is there would not work.
if(condition){
//do something
} else {
//do something else
}
The main issue you are experiencing is proper syntax for arrays in PHP. Thus this will solve your fatal error.
//old
$_POST("Submit_button")
//new
$_POST['foo']
This fixes your first fatal error; conversely, will not get you much further. Since your form is using 'GET' not 'POST' to send the variables to the script. The submit button does not return a variable; rather, use another <input> or add a name to the form <form name="form" action="file.php" method="post"> to retrieve a variable. Hence using:
if(isset($_POST['form'])){
echo $_POST['name'];
}
Furthermore, there are many concerns using $_GET variables and mysql_connect. I would suggest using Google to find some good tutorials on PHP mysqli or PDO before moving on.

How to do a q&a validation in php with cookies

I would like create a script that is somewhat like a login. Before going to a certain page, they must answer a question correctly. If they get it right, then they proceed to the page. For example "What's your mom's name?" If the mom's name is Laurie, then they must enter this into a textbox and get it right to proceed.
Update
I used the script that oliver moran gave me to accomplish this. I added more questions so there is currently one question per page. After the final question has been answered, I have the page targeted to a place where they login, because I couldn't figure out how to do this simply based on the answer of the question. And I am fine with having the user login as a separate function. I have gotten the form to get them to login, and not let users that aren't logged in get to these pages. And the script works as long as they have kept the browser window open.
I have used the link that Oliver Moran gave on using sessions, and you can see in my code that I use sessions. But this does not solve the problem of keeping them logged in.
I would now like to know how to set a cookie once the user has logged in so they can leave the browser window and come back and still be logged in. I have searched this site for an answer, and couldn't find one that made sense. Here is my login code
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
if ($username&&$password) {
$connect = mysql_connect("127.0.0.1","root","") or die('Couldn\'t Connect to Database');
mysql_select_db ("login") or die('Couldn\'t find database');
$query = mysql_query("SELECT * FROM members WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0) {
while($rows = mysql_fetch_assoc($query)){
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
}
if ($username==$dbusername&&$password==$dbpassword) {
echo "Login Successful. <a href='home.php'>Click here for the members area</a>";
$_SESSION['username'] = $dbusername;
}
else{
echo "Incorrect Password";
}
}
else{
die("Incorrect Username and Password");
}
}
else{
die("Please enter something in the boxes");
}
?>
Typically, a server-side language is used for this kind of thing. This is because, if you do password checking in JavaScript, anybody can see the correct password (since all the code is available by looking at the page's source code).
In order to do it securely, you'll need to submit the answer to a server and use a server-side language to check the answer. The server-side script then decides what response to give back to the user.
PHP is a very popular language for server side scripting. Here's the basics:
First we need a log in page (login.html) that has a HTML form in it, like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Login</title>
</head>
<body>
<form action="script.php" method="post">
<label>Enter your mom's name: <input type="text" name="mom" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
The important part here is the form. When the form is submitted, the data is sent to a PHP script called script.php.
That script looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Check login</title>
</head>
<body>
<?php
$mom = $_REQUEST['mom'];
$correct_answer = "Barbie";
if (!isset($mom) || $mom != $correct_answer) {
// nothing was submited or the name was incorrect
echo '<p>That\'s the wrong answer. Try again.</p>';
} else {
echo '<p>Welcome! That\'s the right answer.</p>';
}
?>
</body>
</html>
This is a fairly simple script. It checks what was submitted for 'mom'. If nothing was submitted or it was the wrong answer then a 'try again' message is shown. Otherwise, a 'welcome' message is shown.
The PHP logic (and so the correct answer) will not be visible in a web browser. Only the 'try again' or 'welcome' message will be sent down from the server.
This is the basics of working with HTML forms on the server side. I suggest you read up on using PHP. It's an easy and fun language (if inelegant, in my opinion). You can learn the basics here:
http://www.w3schools.com/php/default.asp
To test your code, you will need a web server. You can download and install a fully-fledged web server with PHP and MySQL (a database) from here:
http://www.wampserver.com/en/
With that, you can develop at test server-side code on your own machine. To test the above example, copy the code above into two files, called login.html and script.php, and put them into the www directory of WAMP.
Good luck!
This is what I managed to come up with. At the top of the page, insert this code before the <!DOCTYPE html>
<?php
//Check for existance of cookie from right answer
if(isset($_COOKIE['parents'])){
header("Location:q1.html");//Move on to next question
}
//Checks answer
if(array_key_exists("dad", $_POST) && array_key_exists('mom', $_POST)){
$dad = $_POST["dad"];
$mom = $_POST["mom"];
$dcorrect = array("Dad", "dad");
$mcorrect = array("Mom", "mom");
if(in_array($dad, $dcorrect) && in_array($mom, $mcorrect)){
setcookie('parents', '1' ,time()+60*60*24);
header("Location: index.html");
}else{
$wrong="<div class='error'>Wrong answer</div>";
}
}
?>
With this HTML
<form action="index.html" method="post">
<label>Enter your father's name:</label>
<input required autocomplete="off" type="text" name="dad" placeholder="Bill">
<label>Enter your mother's name:</label>
<input required autocomplete="off" type="text" name="mom" placeholder="Billette">
<input type="submit" value="Press me when you think you are right" />
<?php echo $wrong; ?>
</form>

php - filling in form fields from database values

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

Form to form with PHP

I am trying to create a multi steps form where user will fill the form on page1.php and by submitting can go to page2.php to the next 'form'. What would be the easiest way?
Here is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
<form id="pdf" method="post">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
if ($_POST["pr_name"]!="")
{
// data collection
$prname = $_POST["pr_name"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, enddate, sel, content) VALUES(?,?,?,?)");
if (!$stmt) echo "\nPDO::errorInfo():\n";
$stmt->execute(array($prname,$prend, $prmenu, $prcontent));
}
// somehow I need to check this
if (data inserted ok) {
header("Location: pr-pdf2.php");
}
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
I have changed following Marc advise, but I don't know how to check if the SQL INSERT was OK.
Could give someone give me some hint on this?
thanks in advance
Andras
the solution as I could not answer to my question (timed out:):
Here is my final code, can be a little bit simple but it works and there are possibilities to check and upgrade later. Thanks to everyone especially Marc.
<form id="pdf" method="post" action="pr-pdf1.php">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
Email subject:<input type="text" name="pr_subject" placeholder="must be filled..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
include_once "ckeditor/ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
$CKEditor->textareaAttributes = array(“cols” => 80, “rows” => 10);
$CKEditor->replace("pagecontent");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// data collection
$prname = $_POST["pr_name"];
$prsubject = $_POST["pr_subject"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, subject, enddate, sel, content) VALUES(?,?,?,?,?)");
// error checking
if (!$stmt) echo "\nPDO::errorInfo():\n";
// SQL command check...
if ($stmt->execute(array($prname, $prsubject, $prend, $prmenu, $prcontent))){
header("Location: pr-pdf2.php");
}
else{
echo"Try again because of the SQL INSERT failing...";
};
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
Add the attribute action with the url you'd like to go to. In this case it'd be
<form id="pdf" method="post" action="page2.php">
EDIT: i missed you saying this method doesn't work. What part of it doesn't work?
You should keep the action to the same script, so the POST action is still performed and then redirect with header("Location: page2.php"); when the processing is done.
A basic structure like this will do it:
form1.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process form data here ...
if (form data ok) {
... insert into database ...
}
if (data inserted ok) {
header("Location: form2.php");
}
}
?>
... display page #1 form here ...
And then the same basic structure for each subsequent page. Always submit the form back to the page it came from, and redirect to the next page if everything's ok.
You're probably better off separating the php code from the form. Put the php code in a file called submit.php, set the form action equal to submit.php, and then add the line header('Location: whateverurl.com'); to your code.
The easiest way is to post it to form2.php by giving the form the attribute action="page2.php". But there's a risk in that. It means that form2 must parse the posted data of form1. Also, if the data is wrong (verification) form1 must be shown instead of form2. This will make your code over complicated and creates dependencies between the two forms.
So the better solution (and quite easy as well) is to implement the post-redirect-get pattern.
You post to form1, verify all data and store it. If the data is ok, you redirect to form2. If the data is wrong, you just show form1 again.
Redirecting is done by a header:
// Officially you'll need a full url in this header, but relative paths
// are accepted by all browsers.
header('Location: form2.php');
Save already posted fields in hidden input fields, but don't forget to validate them every time user submits another step of the form as the user may change hidden inputs in source code.
<input type="hidden" name"some_name" value="submitted_value"/>
There are several ways handling the submitted data while jumping between steps.
You will find your reasons for /against writing data to session, database, whatever... after each step or not.
I did following approach:
The form includes always a complete set of input elements, but on page #1 the step-2-elements are hidden ... and other way round.
I built a 6-step-wizard this way. One large template, some JS /Ajax for validating input, additional hidden inputs that hold current step-ID and PHP deciding, which fields to show or hide.
The benfit in my opinion: Data can easily be saved completely, as soon as input is alright and complete. No garbage handling, if users abort after step 1.
I would store it all in a session array (or sub array)
a really rough example where I'm saving all the form names to an array (to be checked later of course):
<?
foreach($_POST as $k => $v){
$session['register'][$k]=$v;}
?>

Post Back response from PHP to javascript

I'm new to forms and post data ... so I don't know how solve this problem!
I've a php page (page1) with a simple form:
<form method="post" action="/page2.php">
<input type="search" value="E-Mail Address" size="30" name="email" />
<input type="submit" value="Find E-Mail" />
</form>
How you can notice ... this form post the 'email' value to the page2. In the page2 there is a small script that lookup in a database to check if the email address exist.
$email = $_POST['email'];
$resut = mysql_query("SELECT * FROM table WHERE email = $email");
.
.
.
/* do something */
.
.
.
if($result){
//post back yes
}
else{
//post back no
}
I don't know how make the post back in php! And how can I do to the post back data are read from a javascript method that shows an alert reporting the result of the search?
This is only an example of what I'm trying to do, because my page2 make some other actions before the post back.
When I click on the submit button, I'm trying to animate a spinning indicator ... this is the reason that I need to post back to a javascript method! Because the javascript function should stop the animation and pop up the alert with the result of the search!
Very thanks in advance!
I suggest you read up on AJAX.
Here's a PHP example on W3Schools that details an AJAX hit.
Hi i think you can handle it in two ways.
First one is to submit the form, save the data in your session, check the email, redirect
back to your form and display the results and data from session.
Like
session_start();
// store email in session to show it on form after validation
$_SESSION['email'] = $_POST['email'];
// put your result in your session
if ($results) {
$_SESSION['result'] = 'fine';
header(Location: 'yourform.php'); // redirect to your form
}
Now put some php code in your form:
<?php
session_start();
// check if result is fine, if yes do something..
if ($_SESSION['result'] == 'fine) {
echo 'Email is fine..';
} else {
echo 'Wrong Email..';
}
?>
More infos : Sessions & Forms
And in put the email value back in the form field
<input type="search"
value="<?php echo $_SESSION['email']; ?>"
size="30"
name="email" />
Please excuse my english, it is horrible i know ;)
And the other one the ajax thing some answers before mine !
As a sidenote, you definitly should escape your data before using it in an SQL request, to avoid SQL injection
As you are using mysql_* functions, this would be done with one of those :
mysql_escape_string
or mysql_real_escape_string
You would not be able to post in this situation as it is from the server to the client. For more information about POST have a look at this article.
To answer your question you would want to do something like this when you have done your query:
if(mysql_num_rows($result)){ //implies not 0
$data = mysql_fetch_array($result);
print_r($data);
}
else{
//no results found
echo "no results were found";
}
The print_r function is simply printing all the results that the query would have returned, you will probably want to format this using some html. $data is just an array which you can print a single element from like this:
echo $data['email'];
I hope this helps!
<?php
echo " alert('Record Inserted ');"
OR
echo " document.getElementByID('tagname').innerHtml=$result;"
?>
OR
include 'Your Html file name'

Categories