I have a form that will be loaded into a div on another page through AJAX. On click, I would like to check required fields for content. If required fields are not populated, I want to put a message next to the field like in this example: http://www.w3schools.com/php/php_form_required.asp.
If name were required for example, here I would like to add
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name=$_POST['name'];}
On Submit:
<html>
<body>
<?php
// Connect to DB
XXX
$phone=$_POST['phone'];
$category=$_POST['category'];
implode(',',$_POST['check']);
//or something like
$checkstring="";
foreach($_POST['check'] as $checkboxes) {
$checkstring.= $checkboxes .",";
}
$c = rtrim($checkstring);
$query = "INSERT INTO contact VALUES ('$name','$phone', '$c', '$category')";
mysql_query($query) or die('Error, insert query failed');
echo "Hi! $name. Your phone number <b> $phone </b> is in our database";
?>
</body>
</html>
And here I would add
<?php echo $nameErr;?>
next to the name field.
But when I put
?>
in the php variable, it breaks up the variable because it thinks I am ending the
<?php
at the top of Form.
Form:
<?php
// Get value of clicked button
$button = $_GET['button'];
$test = '<center>
<table>
<tr>
<td style="height: 20px;"></td>
</tr>
</table>
<h1>Demo</h1>
<form id="ContactForm" onsubmit="return submitForm();">
<div class="form_result"> </div>
Name: <input name="name" type=text ><br>
Phone: <input name="phone" type=text ><br>
Business Capabilities:<br>
<input type="checkbox" name="check[]" value="c1">C1<br>
<input type="checkbox" name="check[]" value="c2">C2<br>
<select name="category">Category:
<option value="d1">D1</option>
<option value="d2">D2</option>
<option value="d3">D3</option>
</select><br>
<input type="submit" >
</form>
</center>
';
print json_encode($test);
?>
Is it possible for me to put that php statement in the php variable? Or is there another way that would be cleaner to do this? Thanks for your help.
You don't need to echo it. You're creating a giant HTML string, just use string concatenation to include your error:
$test = 'blah blah blah '.$nameErr.' blah blah blah';
Before you go any further though, stop and learn about prepared statements - what you're currently doing with your database is very dangerous, and highly susceptible to sql injection attacks. http://www.php.net/manual/en/book.pdo.php
After a long night, I don't have the complete effort to use your code (so I apologize). But I should be able to get you on the right track. I suggest using JSON as a response in your submit.php page that is called by AJAX. So for example, your script could have:
if(empty($_POST["name"])) {
echo json_encode(array(
'error' => 'Name is required.'
));
} else {
// Do form stuff here
echo json_encode(array(
'phone' => $phone
));
}
Then in your AJAX call, you can easily handle your JSON (in a more modular way, allowing you to easily change your responses/layout).
$.ajax('submit.php', {
// Settings
dataType: 'json' // We want JSON response, this will parse it as an object
}).done(function(data) {
if(data.error !== 'undefined') {
alert('Error: ' + data.error);
} else {
alert('Your phone number is ' + data.phone);
}
});
Feel free to ask if you need more explanation on what I am doing here.
Related
i have a file 'colecting-data.html' with this code :
<html>
<body>
<form action="collect.php" method="get">
name : <input type="text" name="name">
email : <input type="text" name="email">
telephone: <input type="text" name="telephone">
<input type="submit" value="save">
</form>
</body>
</html>
i when to creat "collect.php" file to collect all the data (name email telephone)
and save then in another file "save.html" inside a table .
it will help me a lot if any one know how to do that .
Very quick & dirty answer, remember to sanitize your inputs.
<?php
//collect.php
$html = "<html><head><title>Test</title></head><body><table>";
foreach($_REQUEST as $k=>$v) {
$html .= "<tr><td>$k</td><td>$v</td></tr>";
}
$html .= "</table></body></html>";
file_put_contents('save.html',$html);
?>
As you can use this to learn, start with the basic way to do this before going for more advanced options...
First off, your form needs to be a POST, not a GET.
<form action="collect.php" method="POST">
This will POST the values to collect.php.
On collect.php, you'll need to collect the values;
<?php
if(isset($_POST['name']) {
// Do Something
;}
if(isset($_POST['email']) {
// Do Something
;}
if(isset($_POST['telephone']) {
// Do Something
;}
?>
From here, you can set the posted values as variables and then do whatever you want with them.
there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.
I'm trying to create a contact form so people can leave messages on a website. Essentially I want it to be a single page process with a success or error message appearing on the same page. However, I'm a beginner in PHP so I'm not sure where to go from where I'm currently stuck at.
So far I've gotten the form to submit but always returns with missing fields even though no fields are missing. Also the page reloads and returns to the top of the page. Is there a way, after form submission, to have it not return to the top of the page after form submission?
Here's the HTML form, essentially it's a single page website segmented into different slides. Upon form submission I want the page to stay on slide4 where the form and success/error message will be.
<div id="slide4">
<div class="slidetitle">Contact Me</div>
<div class="content">
<form action="index.php" method="POST" id="contactform" target="_self">
<input type="hidden" name="postid" value="<?php $postid?>">
<table>
<tr><td><b>First Name:</b></td><td><input type="text" name="firstName" size="45" value="<?php $firstName?>"></td></tr>
<tr><td><b>Last Name:</b></td><td><input type="text" name="lastName" size="45" value="<?php $lastName?>"></td></tr>
<tr><td><b>Email:</b></td><td><input type="email" name="email" size="45" value="<?$email?>"></td></tr>
<tr><td><b>Phone:</b></td><td><input type="tel" name="phone" size="45" value="<?$phone?>"></td></tr>
<tr><td><b>Content:</b></td><td><textarea name="content" form="contactform" rows="10" cols="100"><?php echo $content; if (empty($content)){ echo "Enter text here...";} ?></textarea></td></tr>
<tr><td colspan=2 style="text-align: center"><input type=submit name="submit1" value="Leave me a message"></td></tr>
</table>
</form>
<div id="contactoutput">
<?php $output ?>
</div>
</div>
</div>
And here's the Updated PHP for the form after implementing the changes Frank suggested.
<?php
$firstName = "";
$lastName= "";
$email = "";
$phone = "";
$content = "";
$errMsg = "";
?>
<?php $errMsg ?>
<?php
if (isset($_POST['submit1'])) {
// ==========================
//validate user input
// set up the required array
$required = array("firstName","lastName","email","phone","content"); // note that, in this array, the spelling of each item should match the form field names
// set up the expected array
$expected = array("firstName","lastName", "email","phone","content","postid"); // again, the spelling of each item should match the form field names
$missing = array();
foreach ($expected as $field){
// isset($_POST[$field]): Note that if there is no user selection for radio buttons, checkboxes, selection list, then $_POST[$field] will not be set
// Under what conditions the script needs to record a field as missing -- $field is required and one of the following two (1) $_POST[$field] is not set or (2) $_POST[$field] is empty
//echo "$field: in_array(): ".in_array($field, $required)." empty(_POST[$field]): ".empty($_POST[$field])."<br>";
if (in_array($field, $required) && (!isset($_POST[$field]) || empty($_POST[$field]))) {
array_push ($missing, $field);
} else {
// Passed the required field test, set up a variable to carry the user input.
// Note the variable set up here uses a variable name as the $field value. In this example, the first $field in the foreach loop is "title" and a $title variable will be set up with the value of "" or $_POST["title"]
if (!isset($_POST[$field])) {
//$_POST[$field] is not set, set the value as ""
${$field} = "";
} else {
${$field} = $_POST[$field];
}
}
}
//print_r ($missing); // for debugging purpose
/* add more data validation here */
// ex. $price should be a number
/* proceed only if there is no required fields missing and all other data validation rules are satisfied */
$stmt = $conn->stmt_init();
$sql = "Insert Into msg_table16 (firstName, lastName, email, content, phone, postid) values (?, ?, ?, ?, ?, ?)";
if($stmt->prepare($sql)){
// Note: user input could be an array, the code to deal with array values should be added before the bind_param statement.
$stmt->bind_param('ssssii',$firstName, $lastName,$email,$content,$phone,$postid);
$stmt_prepared = 1; // set up a variable to signal that the query statement is successfully prepared.
}
if ($stmt_prepared == 1){
if ($stmt->execute()){
$output = "<p>The following information has been saved in the database:<br><br>";
foreach($_POST as $key=>$value){
$output .= "<b>$key</b>: $value <br>"; //$key (form field names) may not be very indicative (ex. lname for the last name field), you can set up the form field names in a way that can be easily processed to produce more understandable message. (ex. use field names like "Last_Name", then before printing the field name, replace the underscore with a space. See php solution 4.4)
}
} else {
//$stmt->execute() failed.
$output = "<p>Database operation failed. Please contact the webmaster.";
}
} else {
// statement is not successfully prepared (issues with the query).
$output = "<p>Database query failed. Please contact the webmaster.";
}
} else {
// $missing is not empty
$output = "<p>The following required fields are missing in your form submission. Please check your form again and fill them out. <br>Thank you.<br>\n<ul>";
foreach($missing as $m){
$output .= "<li>$m";
}
$output .= "</ul>";
}
?>
So in summary, why is the form returning that fields are missing when I would fill them all in so there shouldn't be any missing. AND How do I have the form submit and not reload and return to the top of the page?
I apologize if there is any required information that I did not post in advance, if you guys need anymore code snippets please let me know. Thank you guys!
Just tried to make something of your code. But there are a few things you really need to take a look at:
You are missing some closing tags in your html, for example you are missing a </div> & </form> tag.
You can put all your php code at the top of your page. It's a best practice to seperate your logic from your view.
Proper php opening and closing tags looks like the following : <?php ... ?> not <= or <?
A proper PDO connection looks like this
<?php
try {
$db = new PDO("pgsql:dbname=pdo;host=localhost", "username", "password" );
echo "PDO connection object created";
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
If you want to concatenate a ul to output your errors you will have to do that the as follow:
<?php
$str = '<ul>';
$str .= '<li></li>';
$str .= '<li></li>';
$str .= '</ul>';
?>
The foundation of the errors you are getting are caused by points like the above. Goodluck and ask if you have any more questions.
What about closing the form tag:
<div id="slide4">
<div class="slidetitle">Contact Me</div>
<div class="content">
<form action="index.php#slide4" method="POST" id="contactform">
<input type="hidden" name="postid" value="<?=$postid?>">
<table>
<tr>
<td><b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" size="45" value="<?=$firstName?>">
</td>
</tr>
<tr>
<td><b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" size="45" value="<?$lastName?>">
</td>
</tr>
<tr>
<td><b>Email:</b>
</td>
<td>
<input type="email" name="email" size="45" value="<?$email?>">
</td>
</tr>
<tr>
<td><b>Phone:</b>
</td>
<td>
<input type="number" name="phone" size="45" value="<?$phone?>">
</td>
</tr>
<tr>
<td><b>Content:</b>
</td>
<td>
<textarea name="content" form="contactform" rows="10" cols="100">
<?php echo $content; if (empty($content)){ echo "Enter text here...";} ?>
</textarea>
</td>
</tr>
<tr>
<td colspan=2 style="text-align: center">
<input type=submit name="submit1" value="Leave me a message">
</td>
</tr>
</table>
</form> <!-- MISSING !! -->
</div>
</div>
i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.
I am just starting to learn php, how would I initiate a echo statement after a submit button is pushed, or even a anchor tag.
Here is my code so far
form name="myform" method="get" actions="madlib01.php"
Name: <input type="text" name="name" /> <br />
<input type="submit" name="submit" />
form
<?php
$Name = $_GET['name'];
$hello .= "Hello $Name";
echo $hello //I would prefer the echo to happen after the submit button is hit
?>
the correct attribute for your form tag is "action", not "actions"
When the form is submitted, a new request is sent to the server (in your case, using GET).
So to do it all in one page:
form.php:
<form action="form.php" method="GET">
<input type="text" name="name"/>
<input type="submit">
</form>
<?PHP
if (! empty($_GET['name'])){
echo 'Hello, ' . $_GET['name'];
}
?>
You will first need to check if PHP has received your GET parameter using isset or array_key_exists:
if(isset($_GET['name']) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
}
or:
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
} else {
//example: default to something if nothing has been passed
echo "Hello Guest";
}
Also note, if you're submitting to the same page, you can omit the action attribute from your form tag altogether:
<form method="GET">
echo $hello
You've just gained an HTML-injection vulnerability. If someone sends your user to:
http://www.example.com/madlib01.php?name=<script>stealYourCookies()</script>
you've got problems.
Yes, this is a My First PHP Script. That doesn't make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.
The result is that most PHP code out there is full of holes. But there's no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:
echo htmlspecialchars($hello);
I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I'm lazy.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
$name= '';
if (isset($_REQUEST['name']))
$name= trim($_REQUEST['name']);
?>
...
<?php if ($name!=='') { ?>
<p> Hello, <?php h($name); ?>! </p>
<?php } ?>
<form method="get" action="madlib01.php">
<p>
<label for="namefield">Name:</label>
<input id="namefield" type="text" name="name" />
</p>
<p>
<input type="submit" />
</p>
</form>
Now if you say your name is Mister <script>, the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.