validation using javascript in php [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to validate my contact form using JavaScript but I dont know the validation codes and where to include,
I want validations should occur before redirecting to thank_you.php page
Plz help me...
HTML
<fieldset>
<?php include("formcode.php"); ?>
</fieldset>
formcode.php
<form method='post' action="database.php">
NAME: <input type='text' name='name' id='name' />
Email: <input type='text' name='email' id='email' />
Contact: <input type='text' name='contact' id='contact' />
Tour:
<select id="tour" name="tour" >
<option value="">--Select Tours--</option>
<option value="Tour1">Tour1</option>
<option value="Tour2">Tour2</option>
</select><br/>
Location:
<select id="location" name="location" >
<option value="">--Select Your Location--</option>
<option value="Loc1">Loc1</option>
<option value="Loc2">Loc2</option>
</select><br/>
Comment:<br />
<textarea name='comment' id='comment' /></textarea><br />
<input type='submit' value='Submit' />
</form>
database.php
<?php
if( $_POST )
{
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_contact = $_POST['contact'];
$users_tour = $_POST['tour'];
$users_location = $_POST['location'];
$users_comment = $_POST['comment'];
$users_name = mysql_real_escape_string($users_name);
$users_email = mysql_real_escape_string($users_email);
$users_contact = mysql_real_escape_string($users_contact);
$users_tour = mysql_real_escape_string($users_tour);
$users_location = mysql_real_escape_string($users_location);
$users_comment = mysql_real_escape_string($users_comment);
$query = "
INSERT INTO `db_name`.`dbtable` (`id`, `name`, `email`, `contact`, `tour`, `location`, `comment`, `timestamp`, `articleid`)
VALUES ( Null, '$users_name', '$users_email', '$users_contact', '$users_tour', '$users_location', '$users_comment', CURRENT_TIMESTAMP);";
mysql_query($query);
$url = 'thank_you.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
mysql_close($con);
include("mail.php");
}
?>

Perform the validation using javascript before submitting the form as shown below. First give id to your form so you can easily submit via JS
<form method='post' action="database.php" id='frm'></form>
make a call to validate function from the submit button like this
<input type='submit' value='Button' onclick=javacript:validate(); />
<script language=javascript> //easy one by one validation. this allow full control
function validate(){
if (document.getElementById('name').value==''){
alert('name is required');//customize this for your need. You may use div display
return;
}
//repeat the above for each form tags and values
document.getElementById('frm').submit();//submit the form
}
</script>
There are more advanced JQuery plugin for validation, the above is the simple primitive method

Related

PHP form text field to mysql based on selected checkbox [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create sign up form, where it has multiple text field (name, email, phone, ..) and have multiple checkbox options.
I also created multiple tables in mysql database, one for each checkbox.
My goal is to store values in text field to selected checkbox data table.
My question is how can I create if statement to look what checkbox is selected, so it will store input of text field to that table
input.php
<html>
<head>
</head>
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('chk1[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in
receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >
</form>
<form action="page.php" method="POST">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
$qh = mysql_query("select * from all_emails order by id desc");
if (#mysql_num_rows($qh)) { /* the if(#...) syntax makes PHP supress any
warnings that might come out of that function. */
/* mysql_fetch_object(query handle);
* returns an object whose contents are that of one rotw in the
database. */
while ($obj = mysql_fetch_object($qh)) {
echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
}
}
?>
</body>
</html>
page.php
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
mysql_query("insert into all_emails (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>
Here is the if statement I am trying.
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
if( isset($_POST["cars_coffee"] ) ) {
$sql = "INSERT INTO cars_and_coffee (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']‌​."', '".$_POST['phone']."' )");
mysql_query($sql) or die(mysql_error());
}
echo "Record is inserted";
}
?>
Hi use the following code :
NOTE : I highly suggest you to use mysqli or PDO. mysql functions are deprecated and are obsolate.
Please sanitize or safe cast your data before inserting into your database.
Also NOTE: In form I am redirecting to the same form page. Please use the appropriate php file name or routing path.
db_connect.php
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'skerp';
$connection_error = 'Sorry!!! We are experiencing problems with the database settings';
$link = mysqli_connect($host, $user, $password, $database) or DIE($connection_error);
The following is the implementation
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include_once ('db_connection.php');
if(in_array('cars_coffee', $_POST['chk'])){
$emails = mysqli_query($link, "INSERT INTO all_emails (name, email, car, phone) VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
}else{
//If it fails then put the condition here or you may skip else part
echo 'Not Exists';
}
echo '<pre>';
print_r($_POST);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hope it helps. Happy Coding!
You can use the isset method to check if a checkbox was selected.
if ( isset ( $_POST ["cars_coffee"] ) )
{
// do something
}
if ( isset ( $_POST ["kentucky"] ) )
{
// do something else
}
...
There seems to be a slight problem with your logic because you are using checkboxes to retrieve data from the user. If you want the user to only select one checkbox, use a radio button. That will make them unable to select multiple. If I'm just not understanding you correctly and you really do want users to be able to select multiple boxes, then keep using checkboxes, but change the name attribute of each checkbox to be unique. Because right now, every checkbox has the same name, so it is going to read only the last checkbox that they checked.
The logic would go something like this if you continued using checkboxes and gave each checkbox a unique name:
$sql = '';
// make sure that the checkbox is set
if(isset($_POST['kentucky_checkbox'])){
{
$sql += 'INSERT INTO kentucky VALUES ...;';
}
if(isset($_POST['labor_checkbox'])){
{
$sql += 'INSERT INTO labor VALUES ...;';
}
etc.
...
// execute $sql
The logic would go something like this if you used radio buttons:
// make sure that the variable is set
if(isset($_POST['chk[]'])){
{
// check what the value is
switch ($_POST['chk[]']) {
case 'option1':
// set the table
$table = 'table1';
break;
case 'option2':
$table = 'table2';
break;
case 'option3':
$table = 'table3';
break;
}
}
...
$sql = 'INSERT INTO ' . $table . ' VALUES ...';

save selected options [<select> values in database

i need to save selected options values in database . In form, I need to include select options inside input type , Basically i have this code.
<form method="post">
<td>Designer order number </td>
<td>
<div id="ordernumbers">
<select>
<option>Select Order</option>
</select>
</div>
</td>
<input type="text" name="dueDate" value=""/>
<input name="register1" type="submit" id="btnSubmit" value="Update"
onclick="return updatepayment(); "/>
</form>
To include select option inside form , i tried as link1 but did't worked for me.
than i followed below code as in mentioned in link2
<form>
<td>
<div id="ordernumbers">
<input type="text" name="designerorder_id" list="citynames">
<datalist id="citynames">
<option>Select Order</option>
</datalist>
</div>
</td>
</form>
still i am getting Notice: Undefined index: designerorder_id error , but instead of above code , if i use this code : <input type="text" name="designerorder_id" /> i am not getting any error, so i guess i am doing in mistake in putting select inside input in form, please help me for this....
EDit
if (isset($_POST['register1'])) {
$designerorder_id = trim($_POST['designerorder_id']);
$product_id = trim($_POST['product_id']);
$paid_status = password_hash($_POST['paid_status'], PASSWORD_DEFAULT);
$due_date = trim($_POST['due_date']);
$stmt = $reg_user->runQuery("SELECT * FROM order_details");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
if ($reg_user->register1($designerorder_id, $product_id, $paid_status, $due_date)) {
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = " updated database";
// $subject = "Confirm updation";
// $reg_user->send_mail($email, $message, $subject);
$msg = "database updated ";
} else {
echo "sorry , Query could no execute...";
}
}
Note : i am requesting downvoter, please inform in comments reason for downvote so that i can correct it....

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

Populating input fields with database info relative to selection from drop down menu

I have a form. In the form I have a drop down menu of peoples names populated from a database. The rest of the form is made up of a few input fields, address, phone, email. This info is also stored in the same database. What I want is when you select a name from the drop down menu the rest of the form fields fill automatically/dynamically with that persons relative data. No refresh, no submit, no go to another page the fields just populate. I think it's an ajax request I need maybe an onChange function on the form but I'm just not sure. Don't want to use jQuery just javascript. I haven't had much success with this and it's driving me mad. Any help would be appreciated. Here is a snippet of my code from the form :
<option value="" selected="selected" class="firstLine">select a name</option>
<?php $query = "SELECT * FROM customers ORDER BY id ASC";
$run = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($run)){
$row['fullname'] = $row['first'].' '.$row['surname'];?>
<option value="<?php echo $row['id'];?>"><?php echo $row['fullname']; ?></option><?php } ?>
</select>
<input type="text" name="address" id="address" value="" disabled="disabled"><br />
<input type="text" name="phone" id="phone" value="" disabled="disabled"><br />
<input type="text" name="email" id="email" value="" disabled="disabled"><br />
An approach I take often is to create a small getData type of service endpoint.
for example in php: *but you could easily do this in c# like I did in the following link.
http://chadcollins.com/json-service-output-from-sql-select-using-c/
create a /services/getData.php file and inside it:
ensure the page only runs if session is authenticated / check authentication
connect to your database and execute the query to the db by passing the sessionUserID into your select.
echo the response in json format
use jquery to handle the ajax (it will be a bit of code do it with native js, but ok if you want.
on the onChange() event in your UI, consider using ajax method to call your services/getData.php script
then using that returned json collection of json data, loop the data and assign the values to your form fields by id.
Notice in my example script how I print out the format needed for a JSON ajax read call. If you want example php code let me know and I can probably pull something together.
This is what you need to do
<option value="" selected="selected" class="firstLine">select a name</option>
<?php $query = "SELECT * FROM customers ORDER BY id ASC";
$run = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($run)){
$row['fullname'] = $row['first'].' '.$row['surname'];?>
<option value="<?php echo $row['id'];?>" onchange="getdata()"><?php echo $row['fullname'];?></option>
<input type="hidden" name="addressinfo" value="<?php echo $row['address']?>">
<input type="hidden" name="phoneno" value="<?php echo $row['phone']?>">
<input type="hidden" name="emailid" value="<?php echo $row['email']?>">
<?php } ?>
</select>
<input type="text" name="address" id="address" value="" disabled="disabled"><br />
<input type="text" name="phone" id="phone" value="" disabled="disabled"><br />
<input type="text" name="email" id="email" value="" disabled="disabled"><br />
now you can use javascript to populate the value to those input boxes
<script>
function myFunction() {
var phone= document.getElementById("phoneno").value;
var address = document.getElementById("addressinfo").value;
var email= document.getElementById("emailid").value;
document.getElementById('phone').value(phone);
document.getElementById('email').value(email);
document.getElementById('address').value(address);
}
</script>

How can I insert information to my MYSQL database from PHP for my website? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to create a new account on my website by using the INSERT INTO mySQL method, in my PHP file. For some reason, the database is not receiving the information I am sending to it. My question is: how can I create a new account with php? The first part of my php code is just validating the text submitted from the html page.
This is my php code which I am using to verify and send data to my database hosted through 000webhost.com.
<?php
$host=""; // Host name (all these are correctly filled in in my code)
$username=""; // username
$password=""; // password
$db_name=""; // Database name
$tbl_name=""; // Table name
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$myusername=mysql_real_escape_string($_POST['username']);
$mypassword1=mysql_real_escape_string($_POST['pass1']);
$mypassword2=mysql_real_escape_string($_POST['pass2']);
$myemail=mysql_real_escape_string($_POST['email']);
$myfirst=mysql_real_escape_string($_POST['first']);
$mylast=mysql_real_escape_string($_POST['last']);
if(!($mypassword2 == $mypassword1)){
$message = "passwords do not match!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else{
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' or email='$myemail'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
echo $myusername;
if($count > 0){
$message = "Username or Email already in use!";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$sql = 'INSERT INTO users (`id`, `username`, `password`, `first`, `last`, `email`, `grade`, `skype`, `phone`, `credentials`)
VALUES (NULL, \'$myusername\', \'$mypassword1\', \'$myfirst\', \'$mylast\', \'$myemail\', NULL, NULL, NULL, NULL);';
$message = "inserted!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
HTML CODE:
<form name="create_account" method ="post" action="php/new_account.php">
<fieldset class="account-info">
<label> First <input type="text" name="first" placeholder="First"> </label>
<label> Last <input type="text" name="last" placeholder="Last"> </label>
<label> Email <input type="text" name="email" id="email" placeholder="Email"> </label>
<label> Username <input type="text" name="username" id="username" placeholder="Username"> </label>
<label> Password <input type="password" name="pass1" id="pass1" placeholder="Password"> </label>
<label> Confirm Password <input type="password" name="pass2" id="pass2" placeholder="Confirm Password" onkeyup="checkPass(); return false;"> </label>
<span id="confirmMessage" class="confirmMessage"></span>
</fieldset>
<fieldset class="account-action">
<input class="btn" type="submit" name="submit" value="Submit">
Login
</fieldset>
</form>
Database image:
http://i.stack.imgur.com/oiwur.png
You are not running a query at all. This is only a string:
$sql = 'INSERT INTO users (`id`, `username`, `password`, `first`, `last`, `email`, `grade`, `skype`, `phone`, `credentials`)
VALUES (NULL, \'$myusername\', \'$mypassword1\', \'$myfirst\', \'$mylast\', \'$myemail\', NULL, NULL, NULL, NULL);';
You need to run it with
mysql_query($sql, $connection);
Also you should put your connection in a variable:
$connection = mysql_connect("$host", "$username", "$password");
You are using a deprecated library. mysql_ is deprecated and you are highly vulnerable to sql injection. You should change your connection to mysqli_ or PDO and use prepared statements!

Categories