Problem :
Hi, I am having a problem with one of my submit form. I have already create a database and I also create a table as well. When I already fill up my form , and click the submit button, and check phpmyAdmin. It doesnt show the details that I already submitted .
This is my php code include the sql connect (reserve.php)
<?php
if($_POST['formSubmit'] === "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li> You forgot to enter your name! </li>";
}
//Doesnt Have List
$varName = $_POST['formName'];
$varEmail = $_POST['formEmail'];
$varPhone = $_POST['formPhone'];
$varStreet = $_POST['formStreet'];
$varNumber = $_POST['formNumber'];
$varCity = $_POST['formCity'];
$varPostCode = $_POST['formPostCode'];
$varCountry = $_POST['formCountry'];
//Have List
$varPeople = $_POST['formPeople'];
$varTables = $_POST['formTables'];
$varTime = $_POST['formTime'];
$varComment = $_POST['formComment'];
if(empty($errorMessage))
{
//Sql Connect
$db = mysql_connect ('sql999.byethost9.com','b9_9999999','password');
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db('b9_9999999_database',$db);
$sql = "INSERT INTO form2 (Name, Email, Phone, Street, Number, City, PostCode, Country, People, Tables, Time, Comment) VALUES (".
//Doesnt Have List Dropdown
PrepSQL($varName) . ", ".
PrepSQL($varEmail) . ", ".
PrepSQL($varPhone) . ", ".
PrepSQL($varStreet) . ", ".
PrepSQL($varNumber) . ", ".
PrepSQL($varCity) . ", ".
PrepSQL($varPostCode) . ", ".
PrepSQL($varCountry) . ", ".
//Have List Dropdown
PrepSQL($varPeople) . ", ".
PrepSQL($varTables) . ", ".
PrepSQL($varTime) . ", ".
PrepSQL($varComment) . ") ";
mysql_query($sql);
header('Location:thankyou.html');
exit();
}
}
//function:PrepSQL()
//use stripslashes and mysql_real_escape_string PHP functions
//tosanitize a string for use in an SQL query
//
//also puts single quotes around the string
//
function PrepSQL($value)
{
//Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
//Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
AND THIS IS MY FORM CODE:
<html>
<?php include("reserve.php"); ?>
<body>
.......
<form action="<?php
echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<!-- PHP-->
<!-- General -->
<div class="form-group">
<h2 class="heading">Booking & contact</h2>
<div class="controls">
<input type="text" id="name" class="floatLabel" name="name" value="<?= $varName;
?>" />
<label for="name">Name</label>
</div>
<div class="controls">
<input type="text" id="email" class="floatLabel" name="email" value="<?= $varEmail;
?>" />
<label for="email">Email</label>
</div>
<div class="controls">
<input type="tel" id="phone" class="floatLabel" name="phone" value="<?= $varPhone;
?>" />
<label for="phone">Phone</label>
</div>
<div class="grid">
<div class="col-2-3">
<div class="controls">
<input type="text" id="street" class="floatLabel" name="street" value="<?= $varStreet;
?>" />
<label for="street">Street</label>
</div>
</div>
<div class="col-1-3">
<div class="controls">
<input type="number" id="street-number" class="floatLabel" name="street-number" value="<?= $varNumber;
?>" />
<label for="street-number">Number</label>
</div>
</div>
</div>
<div class="grid">
<div class="col-2-3">
<div class="controls">
<input type="text" id="city" class="floatLabel" name="city" value="<?= $varCity;
?>" />
<label for="city">City</label>
</div>
</div>
<div class="col-1-3">
<div class="controls">
<input type="text" id="post-code" class="floatLabel" name="post-code" value="<?= $varPostCode;
?>" />
<label for="post-code">Post Code</label>
</div>
</div>
</div>
<div class="controls">
<input type="text" id="country" class="floatLabel" name="country" value="<?= $varCountry;
?>" />
<label for="country">Country</label>
</div>
</div>
<!-- Details -->
<div class="form-group">
<h2 class="heading">Details</h2>
<div class="grid">
<div class="col-1-4 col-1-4-sm">
<div class="controls">
<input type="date" id="arrive" class="floatLabel" name="arrive" value="<?php
echo date('Y-m-d'); ?>">
<label for="arrive" class="label-date"><i class="fa fa-calendar"></i> Arrive</label>
</div>
</div>
</div>
<div class="grid">
<div class="col-1-3 col-1-3-sm">
<div class="controls"> <i class="fa fa-sort"></i>
<select class="floatLabel">
<option value="blank"></option>
<option value="1" <?php if ($varPeople === "Less than 5") echo ("selected=\"selected\""); ?>>Less than 5</option>
<option value="2" <?php if ($varPeople === "More than 5") echo ("selected=\"selected\""); ?>>More than 5</option>
<option value="3" <?php if ($varPeople === "More than 10") echo ("selected=\"selected\""); ?>>More than 10</option>
</select>
<label for="fruit"><i class="fa fa-male"></i> People</label>
</div>
</div>
<div class="col-1-3 col-1-3-sm">
<div class="controls"> <i class="fa fa-sort"></i>
<select class="floatLabel">
<option value="blank"></option>
<option value="deluxe" <?php if ($varTables === "Indoor") echo ("selected=\"selected\""); ?>>Indoor</option>
<option value="Zuri-zimmer" <?php if ($varTables === "Outdoor") echo ("selected=\"selected\""); ?>>Outdoor</option>
<option value="Zuri-zimmer" <?php if ($varTables === "VIP Room") echo ("selected=\"selected\""); ?>>VIP Room</option>
</select>
<label for="fruit">Tables</label>
</div>
</div>
<div class="col-1-3 col-1-3-sm">
<div class="controls"> <i class="fa fa-sort"></i>
<select class="floatLabel">
<option value="single-bed" <?php if ($varTime === "Breakfast") echo ("selected=\"selected\""); ?>>Breakfast</option>
<option value="double-bed" <?php if ($varTime === "Lunch") echo ("selected=\"selected\""); ?>>Lunch</option>
<!-- Add "selected >Lunch" when not using php code -->
<option value="double-bed" <?php if ($varTime === "Dinner") echo ("selected=\"selected\""); ?>>Dinner</option>
</select>
<label for="fruit">Time</label>
</div>
</div>
</div>
<div class="grid">
<p class="info-text">Please describe your needs e.g. Annual Dinner, Party</p>
<br>
<div class="controls">
<textarea name="comments" class="floatLabel" id="comments"><?= $varComment;
?>
</textarea>
<label for="comments">Comments</label>
</div>
<button type="submit" value="Submit" class="col-1-4">Submit</button>
</div>
</div>
<!-- /.form-group -->
</form>
....
</body>
</html>
Your form field name and in your serve.php name field doesnot match. Your updated Code should be
<?php
if($_POST['formSubmit'] === "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li> You forgot to enter your name! </li>";
}
//Doesnt Have List
$varName = $_POST['name'];
$varEmail = $_POST['email'];
$varPhone = $_POST['phone'];
$varStreet = $_POST['street'];
$varNumber = $_POST['street-number'];
$varCity = $_POST['city'];
$varPostCode = $_POST['post-code'];
$varCountry = $_POST['country'];
//Have List
$varPeople = $_POST['arrive'];
$varTables = $_POST['tables'];
$varTime = $_POST['time'];
$varComment = $_POST['comments'];
if(empty($errorMessage))
{
//Sql Connect
$db = mysql_connect ('sql999.byethost9.com','b9_9999999','password');
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db('b9_9999999_database',$db);
$sql = "INSERT INTO form2 (Name, Email, Phone, Street, Number, City, PostCode, Country, People, Tables, Time, Comment) VALUES (".
//Doesnt Have List Dropdown
PrepSQL($varName) . ", ".
PrepSQL($varEmail) . ", ".
PrepSQL($varPhone) . ", ".
PrepSQL($varStreet) . ", ".
PrepSQL($varNumber) . ", ".
PrepSQL($varCity) . ", ".
PrepSQL($varPostCode) . ", ".
PrepSQL($varCountry) . ", ".
//Have List Dropdown
PrepSQL($varPeople) . ", ".
PrepSQL($varTables) . ", ".
PrepSQL($varTime) . ", ".
PrepSQL($varComment) . ") ";
mysql_query($sql);
header('Location:thankyou.html');
exit();
}
}
//function:PrepSQL()
//use stripslashes and mysql_real_escape_string PHP functions
//tosanitize a string for use in an SQL query
//
//also puts single quotes around the string
//
function PrepSQL($value)
{
//Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
//Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
This will solve your problem
Related
In my app I want the user to mention how many columns he wants for the table and then enter the data for those columns and create a table with those values.
Here is what I have:
<form action="" method="post">
<label for="numOfCols">Enter Number of Fields</label>
<input name="numOfCols" type="number" id="numOfCols">
<button type="submit" class="btn btn-info" name="numOfColsSubmit" >Generate</button>
</form>
<?php if(isset($_POST["numOfCols"])): ?>
<form action="" method="post">
<label for="tbName">Enter Layout Name</label>
<input type="text" name="tbName" id="tbName" class="form-control">
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<div class="row g-4">
<div class="col-sm">
<label for="col_name<?php $colNum ?>">Name</label><br>
<input class="form-control" id="col_name<?php $colNum ?>" type="text"
name="col_name<?php $colNum ?>" >
</div>
<div class="col-sm">
<label for="col_types<?php $colNum ?>">Type</label><br>
<select name="col_types<?php $colNum ?>" class="form-control" id="col_types<?php $colNum ?>">
<option value="int">INT</option>
<option value="varchar" >VARCHAR</option>
<option value="text">TEXT</option>
</select>
</div>
<div class="col-sm">
<label for="col_length<?php $colNum ?>">Length</label><br>
<input type="text" class="form-control" name="col_length<?php $colNum ?>" id="col_length<?php $colNum ?>">
</div>
<div class="col-sm">
<br><button type="submit" class="btn btn-success" name="submitaddcol<?php $colNum ?>">Submit</button>
</div>
</div>
<?php endfor; ?>
<button type="submit" name="createtb" class="btn">Create Layout</button>
</form>
<?php endif;?>
<?php if(isset($_POST["tbName"])){
$table->createTb($_POST['tbName']);
} ?>
and the function for creating the table :
function createTb($tb){
$arr = [];
if(isset($_POST['col_name'])){
$colName = $_POST['col_name'];
}
if(isset($_POST['col_types'])){
$colTypes = $_POST['col_types'];
}
if(isset($_POST['col_length'])){
$colLength = $_POST['col_length'];
}
echo $tb;
array_push($arr , $colName , $colTypes , $colLength);
$stmt = $this->pdo->prepare("CREATE TABLE $tb ($colName $colTypes($colLength)) ");
$stmt->execute([$_POST['name'], 29]);
$stmt->execute();
$stmt = null;
}
I was thinking of getting the data from the user, pass it to an array and then use that array in my query.
The problem is I cannot get all of the user data. If the user has 2 or more columns, it will always get the last column. Any insight?
(Putting the createTb($_POST['tbName']) inside the for loop for some reason results in now showing or calling the function at all)
You can name your input-fields as an array like:
<input type="text" name="col_name[]" value="foo" />
And get it with var_dump($_POST['col_name']);
In your example you could do like this:
<?php $numOfCols = $_POST["numOfCols"];
for ($colNum = 0 ; $colNum < $numOfCols ; $colNum++): ?>
<input class="form-control" id="col_name_<?=$colNum ?>" type="text" name="col_name[<?=$colNum ?>]" >
<input type="text" class="form-control" name="col_length[<?= $colNum ?>]" id="col_length_<?=$colNum ?>">
<?php endfor; ?>
And get the result:
if(isset($_POST['col_name']) && is_array($_POST['col_name'])) {
for($i = 0; $i < count($_POST['col_name']); $i++) {
var_dump($_POST['col_name'][$i]);
var_dump($_POST['col_length'][$i]);
}
}
I have a one page php webmail script.
PHP script code below:
<?php
function validEmail($email){
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
return false;
}
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false;
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
if (isset($_POST["submit"])) {
$ip=$_SERVER['REMOTE_ADDR'];
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$company = $_POST['company'];
$address = $_POST['address'];
$state = $_POST['state'];
$city = $_POST['city'];
$pincode = $_POST['pincode'];
$package = $_POST['package'];
$logo = $_POST['logo'];
$writeup = $_POST['writeup'];
$heared = $_POST['heared'];
$call = $_POST['call'];
$message = $_POST['message'];
$mailheader = "From: $email \r\n";
$formcontent .= "IP Address: $ip \n\n Full Name: $name \n E-mail: $email \n Mobile: $mobile \n Company: $company \n Address: $address \n state: $state \n City: $city \n Pin Code: $pincode \n Package: $package \n Logo: $logo \n Write-Ups: $writeup \n Heared: $heared \n Call Back: $call \n\n Message: $message";
$recipient = "***#***.com";
$subject = "Package Enquiry Form";
if (!$_POST['name']) {
$errName = 'Please enter your full name';
}
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['mobile']) {
$errMobile = 'Please enter your mobile number';
}
if (!$_POST['company']) {
$errCompany = 'Please enter your company name';
}
if (!$_POST['address']) {
$errAddress = 'Please enter your Address';
}
if (!$_POST['state']) {
$errState = 'Please enter your state';
}
if (!$_POST['city']) {
$errCity = 'Please enter your city';
}
if (!$_POST['pincode']) {
$errPinCode = 'Please enter your pin code';
}
if (!$_POST['package']) {
$errPackage = 'Please enter your package';
}
if (!$_POST['logo']) {
$errLogo = 'Do you want logo';
}
if (!$_POST['writeup']) {
$errWriteup = 'Do you need writeup';
}
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($recipient, $subject, $formcontent, $mailheader) or die("Error!")) {
$result='<div class="alert alert-success"><button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>Thank You! for placing your order with us. We will revert back to you shortly.</div>';
} else {
$result='<div class="alert alert-danger"><button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>Warning! There was a problem with your network connection. Please try again.</div>';
}
}
}
?>
and the html form code below:
<div class="form-group">
<div class="col-lg-12 col-sm-12">
<strong><?php echo $result; ?></strong>
</div>
</div>
<form id="registerform" method="post" name="registerform" action="">
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Full Name</label>
<input type="text" class="form-control" name="name" placeholder="Full Name *">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>E-Mail Address</label>
<input type="email" class="form-control" name="email" placeholder="Email *">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Contact Number</label>
<input type="number" class="form-control" name="mobile" placeholder="Mobile Number *">
<?php echo "<p class='text-danger'>$errMobile</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Company Name</label>
<input type="text" class="form-control" name="company" placeholder="Company Name *">
<?php echo "<p class='text-danger'>$errCompany</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Address</label>
<input type="text" class="form-control" name="address" placeholder="Address *">
<?php echo "<p class='text-danger'>$errAddress</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>City</label>
<input type="text" class="form-control cities" name="city" placeholder="City *">
<?php echo "<p class='text-danger'>$errCity</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>State</label>
<input type="text" class="form-control" name="state" placeholder="State *">
<?php echo "<p class='text-danger'>$errState</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Pin Code</label>
<input type="number" class="form-control" name="pincode" placeholder="Pin Code *">
<?php echo "<p class='text-danger'>$errPinCode</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Package</label>
<select class="form-control" name="package" size="1">
<option value="" selected="true" disabled="disabled">Choose Your Package *</option>
<option value="Basic Package">Basic Package</option>
</select>
<?php echo "<p class='text-danger'>$errPackage</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Logo</label>
<select class="form-control" name="logo" size="1">
<option value="" selected="true" disabled="disabled">Do you have Logo *</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
<option value="Required">Required</option>
</select>
<?php echo "<p class='text-danger'>$errLogo</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>Write-up Text</label>
<select class="form-control" name="writeup" size="1">
<option value="" selected="true" disabled="disabled">Do you have Write-ups *</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
<option value="Required">Required</option>
</select>
<?php echo "<p class='text-danger'>$errWriteup</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-3 col-sm-6">
<label>For our records</label>
<select class="form-control" name="heared" size="1">
<option value="" selected="true" disabled="disabled">Where you heared about us?</option>
<option value="Google Search">Google Search</option>
<option value="Others">Others</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 ">
<label>Write your Message</label>
<textarea id="message" class="form-control" name="message" rows="5" placeholder="Describe your details enquiry *"></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-lg-6 ">
Request a phone call from a Company representative -
Yes: <input type="radio" value="Yes" name="call">
No: <input type="radio" value="No" name="call">
</div>
</div>
<div class="form-group">
<div class="col-lg-6 text-left">
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-default btn-lg button">
<input type="reset" class="btn btn-default btn-lg button" value="Clear">
</div>
</div>
</form>
</div>
</div>
This above code are in same page. Now i want to add captcha here and the captch code will be : captcha.php
<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165);
$fg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5, $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
and validate code will be: validate.php
<?php
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
}
else
{
die("Wrong Code Entered");
}
?>
and the HTML code of CAPTCHA will be:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
My question i integrate all this code in above page but the after validating page it goes to another page, and i want to it remains in same page after successful mail sent.
I'm trying to keep textbox, select option and textarea values, after submit form without clicking on the reCAPTCHA box. It will keep the textbox, select option and textarea as i wish. but when the textarea has line breaks it will not appear text in the textarea.
php
<?php
session_start();
if(isset($_POST['submit'])){
if(isset($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'site secret key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
//contact form submission code
$name = $_POST['username'];
$replyto = $_POST['emailadd'];
$subject = $_POST['selectOption'];
$message = nl2br($_POST['message']);
$_SESSION['username'] = $name;
$_SESSION['replyto'] = $replyto;
$_SESSION['subject'] = $subject;
$_SESSION['message'] = $message;
if($responseData->success){
$email = "info#email.com";
$to = "info#email.com";
$headers = 'From:'.$name.' <'.$email.'>'."\r\n".'Reply-To:'.$replyto. "\r\n".'X-Mailer: PHP/' . phpversion();
mail($to,$subject,$message,$headers);
$succMsg = 'Your contact request have submitted successfully.';
session_destroy();
echo "<script type='text/javascript'>alert('$succMsg'); window.location = '/'; </script>";
}
else{
$flag = 1;
echo "<script type='text/javascript'>window.location = '#contactus';</script>";
}
}
else{
$flag = 1;
echo "<script type='text/javascript'>window.location = '#contactDiv';</script>";
}
}?>
< script type = "text/javascript" >
$(document).ready(function() {
$("#errorcaptcha").hide();
var flag = '<?php echo $flag; ?>';
var usernmae = "<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];} ?>";//working fine
var email = "<?php if(isset($_SESSION['replyto'])){echo $_SESSION['replyto'];} ?>";//working fine
var subject = "<?php if(isset($_SESSION['subject'])){echo $_SESSION['subject'];} ?>";//working fine
var message = "<?php if(isset($_SESSION['message'])){echo $_SESSION['message'];} ?>"; //error here, works when without line breaks text
if (flag == 1) {
$("#errorcaptcha").show();
$('#username').val(usernmae);
$('#emailadd').val(email);
$('#selectOption').val(subject);
$('#message').val(message);
}
}); < /script>
<!DOCTYPE html>
<html lang="en">
<body id="page-top">
<form id="contactfrom" method="post">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="username" id="username" maxlength="40" required="required" type="text" placeholder="Your name" value="" /> </div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" id="emailadd" name="emailadd" required="required" type="email" maxlength="50" placeholder="Your email" />
</div>
</div>
<label for="username" class="uname" data-icon="u">Inquiry about</label>
<div class="form-group">
<div class="col-sm-12">
<select name="selectOption" id="selectOption" class="form-control">
<option value="1" selected="">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<textarea maxlength="500" id="message" name="message" placeholder="Massage" class="form-control" rows="5" required="required"></textarea>
</div>
</div>
<div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label id="errorcaptcha" for="">Please click on the reCAPTCHA box.</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-12" id="recaptcha">
<div class="g-recaptcha" data-theme="dark" data-sitekey="sitekey"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
Store in session you original $_POST['message']:
Replace
$message = nl2br($_POST['message']);
with
$message = $_POST['message'];
Then after format for your e-mail with nl2br:
mail($to,$subject,nl2br($message),$headers);
Finally i found my own way. textarea doesn't have a value. helpful link here
<textarea maxlength="500" id="message" type="text" name="message" placeholder="Massage" class="form-control" rows="5" required="required"><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']):'' ?></textarea>
I am trying to pass my JavaScript variable using Ajax into my PHP script but that doesn't work it given me error that it is undefined index. both codes are in different files but both of them are accessible on the main page.
Here's my script.php
<script>
function get_child_options(){
var parentID = jQuery('#parent').val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {parentID : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
And this is my php file
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ **/core/init.php'; //Including database path stored in init.php
$parentID = (int)$_POST['parentID'];
$childQuery = "SELECT * FROM categories WHERE parent = '$parentID' ORDER BY category";
ob_start();
?>
<option value="">Select <strong>Child</strong> Category</option>
<?php while ($child = mysqli_fetch_assoc($childQuery)): ?>
<option value="<?= $child['id']; ?>"><?= $child['category']; ?></option>
<?php endwhile; ?>
<?php
echo ob_get_clean();
?>
in script the #parent is a form id i am passing to javascript using jQuery.
because of variable is not accessible PHP is not running query.
This is my products.php the main where page where this is happening
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/Online Store/core/init.php'; //Including database path stored in init.php
include 'includes/head.php'; //Including header
include 'includes/navigation.php'; //Including Navigation bar
include 'includes/script.php';
if (isset($_GET['add'])) {
$brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
$parentQuery = $db->query("SELECT * FROM categories WHERE parent = 0 ORDER BY category");
?>
<h2 class="text-center">Add A New Product</h2><hr />
<form action="products.php?add=1" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" class="form-control" id="title" name="title" value="<?= ((isset($_POST['title']))?sanitize($_POST['title']):''); ?>" placeholder="Add a title" />
</div>
<div class="form-group col-md-3">
<label for="brand">Brand*: </label>
<select class="form-control ">
<option value="" <?= ((isset($_POST['brand']) && $_POST['brand'] == '')?' selected':''); ?> >Select Brand</option>
<?php while($brand = mysqli_fetch_assoc($brandQuery)): ?>
<option value="<?= $brand['id']; ?>" <?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id'])?' selected':''); ?> ><?= $brand['brand'] ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*: </label>
<select class="form-control" id="parent" name="parent">
<option value="" <?= ((isset($_POST['parent']) && $_POST['parent'] == '')?' select':''); ?> >Select <strong>Parent</strong> Category</option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value="<?= $parent['id']; ?>" <?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':''); ?> ><?= $parent['category']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="child">Child Category*: </label>
<select id="child" name="child" class="form-control"></select>
<?php include $_SERVER['DOCUMENT_ROOT'].'/Online Store/admin/parsers/child_categories.php'; ?>
</div>
<div class="form-group col-md-3">
<label for="price">Price*: </label>
<input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price']))?sanitize($_POST['price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label for="list_price">List Price*: </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price']))?sanitize($_POST['list_price']):''); ?>" />
</div>
<div class="form-group col-md-3">
<label>Quantity & Sizes</label>
<button class="btn btn-default btn-info form-control" onclick="jQuery('#sizesModal').modal('toggle'); return false;">Quantity & Sizes</button>
</div>
<div class="form-group col-md-3">
<label for="sizes">Sizes & Quantity preview*: </label>
<input type="text" name="sizes" id="sizes" class="form-control" value="<?= ((isset($_POST['sizes']))?$_POST['sizes']:''); ?>" readonly/>
</div>
<div class="form-group col-md-6">
<label for="photo">Photo*: </label>
<input type="file" name="photo" id="photo" class="form-control" />
</div>
<div class="form-group col-md-6">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control" rows="6" placeholder="Description" ><?= ((isset($_POST['description']))?sanitize($_POST['description']):''); ?></textarea>
</div>
<div class="form-group pull-right">
<input type="submit" class="form-control btn btn-success" value="Add Product" />
</div>
<div class="clearfix"></div>
</form>
<?php
}else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults = $db->query($sql);
$product = mysqli_fetch_assoc($presults);
// Featured product
if (isset($_GET['featured'])) {
$id = (int)$_GET['id'];
$featured = (int)$_GET['featured'];
$featuredSql = "UPDATE `products` SET `featured` = '$featured' WHERE `products`.`id` = '$product[id]' ";
$db->query($featuredSql);
// header('Location: products.php');
}
?>
<h2 class="text-center">Products</h2>
Add Product<div class="clearfix"></div>
<hr />
<table class="table table-bordered table-condensed table-striped">
<thead>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Category</th>
<th>Featured</th>
<th>Sold</th>
</thead>
<tbody>
<?php
while($product = mysqli_fetch_assoc($presults)):
$childID = $product['categories'];
$catSql = "SELECT * FROM categories WHERE id = '$childID'";
$result = $db->query($catSql);
$child = mysqli_fetch_assoc($result);
$parentID = $child['parent'];
$pSql = "SELECT * FROM categories WHERE id = '$parentID'";
$presult = $db->query($pSql);
$parent = mysqli_fetch_assoc($presult);
$category = $parent['category'].'~'.$child['category'];
?>
<tr>
<td>
<span class= " glyphicon glyphicon-pencil"></span>
<span class= " glyphicon glyphicon-remove-sign"></span>
</td>
<td><?= $product['title']; ?></td>
<td><?= money($product['price']) ?></td>
<td><?= $category; ?></td>
<td><a href="products.php?featured=<?= (($product['featured'] == 0)?'1':'0'); ?>&id =<?= $product['id']; ?>" class=" btn btn-sx btn-default">
<span class=" glyphicon glyphicon-<?= (($product['featured'] == 1)?'minus':'plus'); ?>"></span>
</a>  <?= (($product['featured'] == 1)?'Featured':''); ?></td>
<td>0</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php
}
include 'includes/footer.php'; //Including footer
?>
Is there any other way to do it? What I am trying to do is when user selects parent category I want child category to arrange as per parent category.
Try this:
<script>
function get_child_options(){
var parentID = $(this).val();
jQuery.ajax({
url: '/**/**/**/child_categories.php',
type: 'POST',
data: {'parentID' : parentID},
success: function(data){
jQuery('#child').html(data);
},
error: function(){alert("Something Went Wrong with child options. ")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
</script>
Getting the Value by $(this) and putting single quotes around parentID data: {'parentID' : parentID},
All columns are in TEXT format apart from the BDid column which is in int. Ive had the code running smoothly with un-preared statements but thought I would update it, with the same data in and the same table.
No errors are returned, but no rows are affected.
The code is not getting any error but the MySQL is not updating
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors with form fields
$first_nameError = null;
$sur_nameError = null;
$companyError = null;
$locationError = null;
$supervisorError = null;
$departmentError = null;
$job_descriptionError = null;
$hire_dateError =null;
$emailError = null;
$messageError = null;
// keep track post values
$first_name = $_POST['first_name'];
$sur_name = $_POST['sur_name'];
$company = $_POST['company'];
$location = $_POST['location'];
$supervisor = $_POST['supervisor'];
$department = $_POST['department'];
$job_description = $_POST['job_description'];
$hire_date = $_POST['hire_date'];
$email = $_POST['email'];
$message = $_POST['message'];
// validate input for the field
$valid = true;
if (empty($first_name)) {
$first_nameError = 'Please enter Name';
$valid = false;
}
if (empty($sur_name)) {
$sur_nameError = 'Please enter Name';
$valid = false;
}
if (empty($company)) {
$companyError = 'Please selest Company';
$valid = false;
}
if (empty($location)) {
$locationError = 'Please enter Location';
$valid = false;
}
if (empty($department)) {
$departmentError = 'Please enter Department';
$valid = false;
}
if (empty($job_description)) {
$job_descriptionError = 'Please enter Job Description';
$valid = false;
}
if (empty($hire_date)) {
$hire_dateError = 'Please enter Hire Date';
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($message)) {
$messageError = 'Please enter Message';
$valid = false;
}
// update data the field in the database
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE employee SET first_name = ?,sur_name = ?, company = ?, location = ?, supervisor = ?,
department= ?, job_description = ?, hire_date = ?, email = ?, message = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id, $first_name, $sur_name, $company, $location, $supervisor, $department,$job_description, $hire_date, $email, $message));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM employee where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$first_name = $data['first_name'];
$sur_name = $data['sur_name'];
$company = $data['company'];
$location = $data['location'];
$location = $data['supervisor'];
$department = $data['department'];
$job_description = $data['job_description'];
$hire_date = $data['hire_date'];
$email = $data['email'];
$message = $data['message'];
Database::disconnect();
}
?>
This my Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Customer</h3>
</div>
This is my form
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($first_nameError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="first_name" required placeholder="First Name"
title="First Name" value="<?php echo !empty($first_name)?$first_name:'';?>">
<?php if (!empty($first_nameError)): ?>
<span class="help-inline"><?php echo $first_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($sur_nameError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="sur_name" required placeholder="Sur Name" title="Sur Name"
value="<?php echo !empty($sur_name)?$sur_name:'';?>">
<?php if (!empty($sur_nameError)): ?>
<span class="help-inline"><?php echo $sur_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($companyError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<select name="company" class="company" id="company" style="company"
title="Company" required placeholder="Company" value="<?php echo !empty($company)?$company:'';?>">
<option value="Select.." selected>Select....</option>
<option>HM</option>
<option>HRA</option>
<option>HSG</option>
<option>HAL</option>
<option>HBN</option>
<option>HFR</option>
<option>HPL</option>
<option>HRD</option>
<option>HERS</option>
<option>HPS</option>
<option>HEA</option>
</select>
<?php if (!empty($companyError)): ?>
<span class="help-inline"><?php echo $companyeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($locationError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="location" required placeholder="Location" title="Location"
value="<?php echo !empty($location)?$location:'';?>">
<?php if (!empty($locationError)): ?>
<span class="help-inline"><?php echo $location;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($supervisorError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="supervisor" required placeholder="Supervisor"
title="Supervisor" value="<?php echo !empty($supervisor)?$supervisor:'';?>">
<?php if (!empty($supervisorError)): ?>
<span class="help-inline"><?php echo $supervisor;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($departmentError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<select name="department" size="1" class="department" id="department" style="department"
title="Department " required placeholder="Department" value="<?php echo !empty($department)?$department:'';?>">
<option value="Select" selected>Select</option>
<option value="FI">Finace</option>
<option value="CO">Controlling</option>
<option value="PP">Production Planning</option>
<option value="SD">Sale & Distribution &Customer Relationship manager</option>
<option value="WM">Warehouse Managerment</option>
<option value="MM">Material Managerment</option>
<option value="HR">Human Resources</option>
<option value="QM">Quality Management</option>
<option value="PM">Plant Maintenance</option>
<option value="IT">Information Technology</option>
<option value="BO">Back Office</option>
<option value="SAP">Administrative Group SAP User</option>
<option value="SAPKEY">Administrative Group SAP Key User</option>
<option value="ADMIN">Administrative Group Administrators</option>
<option value="MGMT">Management</option>
</select>
<?php if (!empty($departmentError)): ?>
<span class="help-inline"><?php echo $department;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($job_descriptionError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="job_description" required placeholder="Job Description"
title="Job Description" value="<?php echo !empty($job_description)?$job_description:'';?>">
<?php if (!empty($job_descriptionError)): ?>
<span class="help-inline"><?php echo $job_description;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($hire_dateError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name= "hire_date" type="date" required placeholder="Hire Date"
title="Hire Date" value="<?php echo !empty($hire_date)?$hire_date:'';?>">
<?php if (!empty($hire_dateError)): ?>
<span class="help-inline"><?php echo $hire_date;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<input name="email" type="email" required placeholder="Email"
title="Email ID" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $email;?></span>
<?php endif; ?>
</div>
</div><div class="control-group <?php echo !empty($messageError)?'error':'';?>">
<label class="control-label"></label>
<div class="controls">
<textarea name="message" cols="20" rows="5" required placeholder="Message"
title="Comments"value="<?php echo !empty($message)?$message:'';?>"></textarea>
<?php if (!empty($messageError)): ?>
<span class="help-inline"><?php echo $messager;?></span>
<?php endif; ?>
</div>
this is the action
</div> <div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
it looks like you need to change the execute line to this:
$q->execute(array($first_name, $sur_name, $company, $location, $supervisor, $department,$job_description, $hire_date, $email, $message, $id));