I want to creat a form which can connect to mysql and can insert records which I have done. But now I want to make some fields mandatory, username and car for example. Also showing the error field as required or "name cannot have numbers". Stuff like that. I am unable to figure it out.
Some help please:
I have index.html
<form action="insert.php" method="post">
Nume: <input type="text" name="name"><span class="error">* <?php echo $error;?></span><br>
Prenume: <input type="text" name="prenume"><br>
Masina: <input type="radio" name="masina" value="vito"> (Vito)
<input type="radio" name="masina" value="skoda"> (Skoda)
<input type="radio" name="masina" value="skoda2"> (Skoda)
<input type="radio" name="masina" value="audi"> (Audi)<br><br>
Data: <input type="date" name="data"/><br>
Ora: <input type="time" name="ora"/><br>
Destinatie:<input type="text" name="destinatie"><br>
KM la iesire: <input type="text" name="kmiesire"><br>
KM la intrare: <input type="text" name="kmintrare"><br>
<input type="submit">
and Insert.php
<?php
include "connect.php";
$order = "INSERT INTO data_employees
(name, prenume, masina, data, ora, destinatie, kmiesire, kmintrare)
VALUES
('$_POST[name]',
'$_POST[prenume]',
'$_POST[masina]','$_POST[data]','$_POST[ora]','$_POST[destinatie]',
'$_POST[kmiesire]','$_POST[kmintrare]'
)";
if (mysqli_query($con,$order)){
header('Location: index.html');
}else{
echo("Input data is fail");
}
?>
you have to check rules before the query...
if(empty($_POST['name'])){
echo "Name Required";
}
elseif(bla bla){
echo "something"
}
else {
// your query....
}
Start checking with ,
if($_POST) {
if(isset($_POST['name'])!='') {
echo 'your error message';
}else if (isset($_POST['prenume'])!='') {
echo 'your error message';
}.....
else
//your insertion code (query)
}
And also you can check with # ,empty like isset .
You have to check that POST values are not empty then there is no injected code to prevent injection attacks.
You should take a look to PDO PHP. It will be more safer than mysql low-level functions and more easy to use.
Related
I am learning PHP MYSql and faced an error while writing a marks submission program. When i run the program in chrome, the table is coming ok but neither the values are inserting in the MySQL table nor the redirection to different webpage taking place. You will understand it more clearly in the code and screen given below
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$connection = mysql_connect("localhost","root","");
if($connection == false)
{
echo("<h3>Unable MySQL</h3>");
die();
}
$db = mysql_select_db("IGNOU",$connection);
if($db == false)
die("<h3>Unable to connect to DB</h3>");
if(isset($_POST['submit']))
{
$rcptno=mysql_real_escape_string($_POST['rcptno']);
$subdt=mysql_real_escape_string($_POST['subdt']);
$amarks=mysql_real_escape_string($_POST['amarks']);
$Vvmarks=mysql_real_escape_string($_POST['Vvmarks']);
$chk_dt=mysql_real_escape_string($_POST['chk_dt']);
$roll_no=mysql_real_escape_string($_POST['roll_no']);
$sbcode=mysql_real_escape_string($_POST['sbcode']);
$ecode=mysql_real_escape_string($_POST['ecode']);
$query1=mysql_query("insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt',
'$roll_no','$sbcode','$ecode')");
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
if($query1)
{
header("location:studentmaster.php");
}
}
?>
<fieldset style="width:400px;">
<form method="post" action="">
Reciept No.: <input type="number" name="rcptno" min="1">
<br>
Submission Date.: <input type="date" name="subdt">
<br>
Assignment Marks: <input type="number" name="amarks" max = "100">
<br>
Viva Marks: <input type="number" name="Vvmarks" max="100">
<br>
Checking Date.: <input type="date" name="chk_dt">
<br>
Roll No.: <input type="text" name="roll_no">
<br>
Subject Code.:
<input type="text" name="sbcode">
<br>
Evaluator Code:
<input type="text" name="ecode">
<br>
<input type="submit" name="submit">
</form>
</fieldset>
</body>
</html>
Screen
[This is the screen in which i have not yet clicked submit button]
[Now i have Clicked Submit button but it only displays a line...no insertion...no redirection]
Kindly help in overcoming this problem....
You're seeing the output because your using this line.
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
Also you need to make sure that you have successfully inserted or not.
For this you should use these lines of code.
if ($query1) {
header('Location: studentmaster.php');
} else {
echo 'No redirect means query failed';
var_dump(mysql_error($connection));
}
Because you're learning you can skip mysql_* functions and move to mysqli, PDO
Just replace the insert query with this
insert into assignment(`col1`,`col2`,`col3`,`col4`,`col5`, `col6`,`col7`,`col8`) values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt', '$roll_no','$sbcode','$ecode')
replace col1, col2, col3... with your mysql table columns
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.
I have a form like below and I want to get some input from the user. My goal is to validate the data before submitting into database. My question is how do I do this ?
<form action="../actions/insertcomment.php" method="post">
<p class ="ctitle">Leave a Comment:</p>
<p><label for="postid"><b>PostID:</b></label>
<input type="text" id="postid" name="postid" maxlength="5" /> <br/>
<label for="name"><b>Name:</b></label>
<input type="text" id="name" name="name" maxlength="25" /> <br/>
<label for="email"><b>Email:</b></label>
<input type="text" id="email" name="email" maxlength="50" /> <br/>
<label for="website"><b>Website:</b></label>
<input type="text" id="website" name="website" maxlength="25" /> <br/>
<label for="content"><b>Comment:</b></label>
<textarea id="content" name="content" cols="10" rows="4" maxlength="100"></textarea> <br/>
<input type="submit" value="Submit Comment" name="submit_comment" /> <br/>
</p>
</form>
and my insercomment.php is as follows:
<html>
<link rel = "stylesheet" type = "text/css"
href = "../common/style.css" />
<?php
include("../common/dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
//$postid= $_GET['id'];
if($_POST) {
$postid= $_POST['postid'];
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
$postid = htmlspecialchars($postid);
$users_name = htmlspecialchars($users_name);
$users_email = htmlspecialchars($users_email);
$users_website = htmlspecialchars($users_website);
$users_comment = htmlspecialchars($users_comment);
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ( $postid, '$users_name',
'$users_email', '$users_website', '$users_comment' )";
//echo $sSql;
mysql_query($sSql);
//$update=mysql_affected_rows();
//echo "<h2>$update Record Inserted</h2><br />";
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
Here I am not using " method="post"> Any code or example for this kind is appreciated.
The best way would be to check if the data is valid, befor the sql statement.
Pseudocude:
$data1 = $_POST['xyz']; //text
$data2 = $_POST['abc']; //number
...
errors = array
if(data1 is not text) errors[] = data1 must be text
if(data2 is not number) errors[] = data2 must be number
...
if(count(errors) > 0) return errors
else
do the sql insert
return "thank you message"
You should certainly sanitize your inputs to prevent injection:
$postid= mysql_real_escape_string($_POST['postid']);
This will make all your inputs safe to insert into the database.
My experience says that you should check your input with if-else statement before doing an insert to DB. The most important thing is to use prepared statement. Don't pass raw strings like that. Always use prepared statement for your forms.
Refer this: Best way to prevent SQL Injection
You can use filter_input to validate data in php. You can read more about it here:
filter_input in php
Here's an example on how to use it to validate an email:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
Where INPUT_POST is the method, email is the name of the field ($_POST['email']) and FILTER_VALIDATE_EMAIL is the validation option.
You might want to consider using prepared statements in mysqli or pdo to make your application more secure.
To check if a variable has a value you can use the function empty:
if(!empty($_POST['email']){
//do stuff
}
You can also add client-side validation. A good library is the liveValidation which as the name suggests validates user input as they type so that the user won't have to wait for the page to refresh before they get feedback whether their form has been successfully submitted or not.
I suggest you use sanitize the strings for SQL injections using mysql_real_escape_string(). Validate using if else statements. Fore example
if ($_POST['name']...)
{
echo "fill in those fields!";
}
else
{
do stuff...
}
By the way you should be using a PDO prepared statement and not echoing HTML with PHP.
You can do like this :-
if(isset($_POST))
{
if($_POST['postid']!="" && $_POST['name']!="" &&.....)
{
//do your insertion here
}
else
echo "oops !! Something is missing";
}
I am working on a system and i want to check if a record exist. If a record exist then it will not record the data and instead will return to the form. If the data does not exist then it will proceed to recording the data to DB.
HTML form:
<form name="studentform" onSubmit="return validate_form ( );" action="queries/insert.php" method="post">
Student Number: <input type="text" name="studentnumber"/>
College:
<select name="college" id=a></select>
Course:
<select name="course" id=b></select>
<input type="radio" name="status" value="regular" />Regular
<input type="radio" name="status" value="irregular" />Irregular
<br><br>
<hr>
<br>
Name:
<input type="text" name="lname">
<input type="text" name="fname">
<input type="text" name="mname">
Address:
<input type="text" name="address" />
<br><br>
Gender:
<select name="gender">
<option value="">---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" value="Submit">
</form>
PHP form:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) >= 1)
{
echo "<script type='text/javascript'>alert('User already exist'); location.href = '../admin_home.php';</script>";
}
}
else{
$sql="INSERT INTO students (studentnumber, college, course, status, lname, fname, mname, address, gender)
VALUES
('$_POST[studentnumber]','$_POST[college]','$_POST[course]','$_POST[status]','$_POST[lname]','$_POST[fname]','$_POST[mname]','$_POST[address]','$_POST[gender]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<script type='text/javascript'>alert('Record Successfully Added'); location.href = '../admin_home.php';</script>";
}
I don't know why but i always get the undefined index error. Maybe i've done something wrong somewhere. Thanks !!
"Undefined index" is referring to your array ($_POST, probably), and it should be a notice, not an error. Can you post the exact message?
In the meantime, switch your first line for
$query = "SELECT studentnumber FROM students where studentnumber = '".mysql_real_escape_string($_POST['studentnumber'])."'";
Also, it's helpful for debugging to print out the query to make sure it looks like you'd expect:
print $query."<br />"; // obviously
[edit]As you've now posted the error message, it becomes far more simple - $_POST['studentnumber'] does not exist. Check your form.
A good way to debug posted results is to use the code
print '<pre>';
print_r($_POST);
print '</pre>';
The problem is in your queries:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$_POST[studentnumber] is not correct. It needs to be $_POST['studentnumber']. Notice the quotes around the key.
I suggest doing it this way:
$query = sprintf("SELECT studentnumber FROM students where studentnumber = '%s'"
, mysql_real_escape_string($_POST['studentnumber']));
Change all your queries accordingly.
try with this:
if( isset($_POST['submit']) ){
$student_num = mysql_real_escape_string( $_POST['studentnumber'] );
// Set all the require form fields here with mysql_real_escape_string() fun
if( !empty($student_num) ){
// Your Query Here
}
else{
echo 'Value not Set in Student Number Field!';
}
}
Edit: first check all the fields after isset($_POST['submit']) so that you confirm about all the values are properly getting or not
after getting all the required values start your query
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.