Php Contact Form Inserting into Mysql - php

LAST EDIT : Everything works now will post below the working code , after clearing up like idealcastle said and fixed some syntax errors everything works as it should together with the javascript validation thank you everyone
HTML Code here :
<form name = "contact " id="contact_form" action="postcontact.php" method="post" onsubmit="return validateForm();">
<div id ="boxc">
<h3>Porosia juaj ?</h3>
<input name="orders" type="checkbox" value="veshje">Veshje
<input name="orders" type="checkbox" value="mbathje">Mbathje
<input name="orders" type="checkbox" value="stoli">Stoli
</div>
<div class="row">
<label class="required" for="name" >Emri:</label><br />
<input id="name" name="name" type="text" value="" size="30" placeholder = "Emri"/><br />
<span id="name_validation" class="error"></span>
</div>
<label class="required" >Country/State:</label><br />
<div class = "row"id="statecmb"><select name = "state">
<option value="chose" selected>[choose yours]</option>
<option value="albania">Albania</option>
<option value="kosovo">Kosovo</option>
<option value="germany">Germany</option>
<option value="bangladesh">Bangladesh</option>
</select>
<span id="state_validation" class="error"></span></div>
<div class="row">
<label class="required" for="email" >Email:</label><br />
<input id="email" name="email" type="text" value="" size="30"placeholder = "Email" /><br />
<span id="email_validation" class="error"></span>
</div>
<div class="row">
<label class="required" for="message" >Mesazhi:</label><br />
<textarea id="message" name="message" rows="7" cols="30" placeholder = "Mesazhi"></textarea><br />
<span id="message_validation" class="error"></span>
</div>
<input name="submit" id = "sub"type="submit" value="Submit" />
<div class="rating">
<h3>Vlerso Sherbimin :</h3>
<input type="radio" name="rate" value="1">1
<input type="radio" name="rate"value="2">2
<input type="radio" name="rate" value="3">3
<input type="radio"name="rate" value="4">4
<input type="radio" name="rate" value="5">5
</div>
</form>
Javascript file :
function validateForm() {
var valid = 1;
var email = document.getElementById('email');
var email_validation = document.getElementById("email_validation");
var name = document.getElementById('name');
var name_validation = document.getElementById("name_validation");
var message_validation = document.getElementById("message_validation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value === "") {
valid = 0;
name_validation.innerHTML = "Ju lutem shenoni emrin tuaj";
name_validation.style.display = "block";
name_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
name_validation.style.display = "none";
name_validation.parentNode.style.backgroundColor = "transparent";
}
if (message.value === "") {
valid = 0;
message_validation.innerHTML = "Ju lutem plotesoni fushen e mesazhit";
message_validation.style.display = "block";
message_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
message_validation.style.display = "none";
message_validation.parentNode.style.backgroundColor = "transparent";
}
if (email.value === "") {
valid = 0;
email_validation.innerHTML = "Ju lutem shenoni email tuaj";
email_validation.style.display = "block";
email_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
email_validation.style.display = "none";
email_validation.parentNode.style.backgroundColor = "transparent";
}
if (!filter.test(email.value)) {
valid = 0;
email_validation.innerHTML = "Email juaj nuk eshte valid";
email_validation.style.display = "block";
email_validation.parentNode.style.backgroundColor = "#FFDFDF";
} else {
email_validation.style.display = "none";
email_validation.parentNode.style.backgroundColor = "transparent";
}
if (!valid)
alert("KENI ERROR : Fushat duhen te plotesohen ");
}
PHP FIle :
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'herdesigns';
$con = mysqli_connect($host, $user, $pass,$db) or die(mysqli_error());
/* mysqli_select_db($con , $db); */
?>
<?php
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
$rate = mysqli_real_escape_string($con, $_POST['rate']);
$orders = mysqli_real_escape_string($con, $_POST['orders']);
$state = mysqli_real_escape_string($con, $_POST['state']);
/*$con = mysqli_connect($host, $user, $pass,$db) or die(mysqli_error());*/
/*mysqli_select_db($con , $db);*/
$sql = "INSERT INTO contacts (
orders,
name,
state,
email,
message,
rate
)
VALUES (
'$orders',
'$name',
'$state',
'$email',
'$message',
'$rate'
)";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Mesazhi juaj eshte postuar me sukses";
header('Location:contact.php');
mysqli_query($con, $sql);
mysqli_close($con);
}
?>

EDIT:
What field is NOW() going too?
I would remove that if there is no actual field to send that datetime. Or add a field for that. Try submitting Mysql without NOW() It would look like
$sql = "INSERT INTO contacts (
name,
email,
message,
rate,
orders,
state
)
VALUES (
'$name',
'$email',
'$message',
'$rate',
'$orders',
'$state'
)";
First thing I notice is the PHP code is being shown in the browser. If you are being sent to file:// that is not good, you should be using
http//localhost/
(if you are testing locally) or of course using the server url if live.
found here
Browser is showing PHP code instead of processing it
Second,
you should sanitize your mysql data being entered. If anyone of those values submits content with a single/double quote, mysql query will fail.
Since you are using an old mysql function, here is the escape function that should work
mysql_real_escape_string()
I would do this,
$sql = "INSERT INTO contacts (
name,
email,
message,
rate,
orders,
state
)
VALUES (
'".mysql_real_escape_string($name)."',
'".mysql_real_escape_string($email)."',
'".mysql_real_escape_string($message)."',
'".mysql_real_escape_string($rate)."',
'".mysql_real_escape_string($orders)."',
'".mysql_real_escape_string($state)."',
NOW()
)";
I am not sure if anyone of these are the cause, but they are red flags from what you have posted. You should always sanitize (escape) any inputs from crashing mysql queries.

It could be an error code 500 on validform.php.
please install firefug on firefox, it will save you lots of time. type [F12] reload the page and the network tab will show you the code of error.
also, you need to get this page by the web server: http://localhost/dir/file instead c://shittyos_amp/dir/thing.php
Plus, You should use the PDO's API for conection and every request with DB as pdo->prepare will secure the request easily for you.
Don't worry it's easy!
see PHP: Is mysql_real_escape_string sufficient for cleaning user input?
Don't say you don't need security: this input form could erase your database if an user type a sql command in it!
Anymore, If the file is client-side executed, it will never protect anythings as JS can be disabled by user.
note: I still consider myself as a noob (it's my first answer here!), never forget that web's moving everday, as security. back-end and and front-end are server-side it's an application point of view: front end= friendly-interface(code) back end=api(hard/or low level code)
PS: flash is ugly and obsolete, Adobe product's aren't free as freedom and their cloud sucks^^ (troll off)
Is it yours? http://www.her-design.com/

Related

How to retrieve and confirm form inputs on another php file

I have The following form inputs I am trying to send these input data to "placebet.php" then retrieve the data and add a confirm or cancel button, then It can add to the database
<form action="placebet.php" method="post">
<div id="box" class="boxlit">
<div class="box" data-id="0">Myanmar - Vietnam<br>Home [1]<div class="crtTotal">4.30</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 10:00">
<input type="hidden" name="match[]" value="Myanmar - Vietnam">
<input type="hidden" name="result[]" value="Home [1]" readonly="">
<input type="hidden" name="value[]" value="4.30"></div>
<div class="box" data-id="4">Thailand - Philippines<br>Draw [2]<div class="crtTotal">3.20</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 13:30">
<input type="hidden" name="match[]" value="Thailand - Philippines">
<input type="hidden" name="result[]" value="Draw [2]" readonly="">
<input type="hidden" name="value[]" value="3.20"></div>
<div class="box" data-id="11">Botswana - Cameroon<br>Away [3]<div class="crtTotal">1.35</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 22:00">
<input type="hidden" name="match[]" value="Botswana - Cameroon">
<input type="hidden" name="result[]" value="Away [3]" readonly="">
<input type="hidden" name="value[]" value="1.35"></div></div><br>
<input type="hidden" name="account[]" value="0818054386" readonly="">
<input type="hidden" name="balance[]" value="20" readonly="">
<input type="hidden" id="todds" name="todds[]" value="18.58" readonly="">
<input type="hidden" id="inp" name="payout[]" value="92.90" readonly="">
<div>Total Odds: <b id="ct1">18.58</b></div><br>
<div>(N$)Stake: <input id="stake" type="number" name="stake[]" value="5"> NAD</div><br>
<div>Payout: N$ <b id="payout">92.90</b></div>
<input class="bet1" type="submit" name="submit" value="Bet">
</form>
Php code in "placebet.php"
I'm not sure if the code below is correct but I need it to show the input data from the form and give me a option to confirm the data(button) and then it can finally add to the database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "forms");
$dba = mysqli_connect("localhost","root","","login");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$error = false; //set the error status value
$error_msg = "";
$back = mysqli_real_escape_string($link, $_REQUEST['kickoff'][0]);
$total = count($back); // get the length of the match
for($i=0;$i<$total;$i++){
// Escape user inputs for security
$kickoff = mysqli_real_escape_string($link, $_REQUEST['kickoff'][$i]);
$match = mysqli_real_escape_string($link, $_REQUEST['match'][$i]);
$selection = mysqli_real_escape_string($link, $_REQUEST['result'][$i]);
$odd = mysqli_real_escape_string($link, $_REQUEST['value'][$i]);
$account = mysqli_real_escape_string($link, $_REQUEST['account'][0]);
$stake = mysqli_real_escape_string($link, $_REQUEST['stake'][0]);
$payout = mysqli_real_escape_string($link, $_REQUEST['payout'][0]);
$todds = mysqli_real_escape_string($link, $_REQUEST['todds'][0]);
$accabal = mysqli_real_escape_string($link, $_REQUEST['balance'][0]);
//run sql query for every iteration
$charge = mysqli_query($dba, "UPDATE users SET balance = $accabal- $stake WHERE username='".$_SESSION['username']."'") ;
$_SESSION["balance"] = $accabal- $stake ;
$date = date ('Ymd');
$create = mysqli_query($link,"CREATE TABLE R$date LIKE receipts") ;
$insert = mysqli_query($link,"INSERT INTO `R$date`(`Match`, `Selection`, `Odd`,`Account`,`Stake Amount`,`Payout`,`Total Odds`) VALUES ('$match','$selection','$odd','$account','$stake','$payout','$todds')");
if(!$insert)
{
$error = true;
$error_msg = $error_msg.mysqli_error($link);
}
//check your error status variable and show your output msg accordingly.
if($error){
echo "Error :".$error_msg;
}else{
header("location: index.php");
exit;
}
}
mysqli_close($db);
?>
What you want to do isn't redirect to index.php, cause with this you start a new request and cant point on the request data of placebet.php anymore.
You want either to send your form via javascript ajax request and then react to the response of placebet.php (https://www.w3schools.com/js/js_ajax_intro.asp) or generating your own new output at placebet.php which then can be a confirm page or something similar.
e.g.
if($error){
echo "Error :".$error_msg;
}else{
echo "Data has been stored!";
}
You also could put your html at the end of the php file after closing the php part with ?> like mentioned here https://www.thoughtco.com/php-with-html-2693952#:~:text=As%20you%20can%20see%2C%20you,re%20inside%20the%20PHP%20tags).

How to use a radio button with PHP to upload certain information to my database?

I have created a form with HTML/PHP/SQL where a user can either choose to submit their email into a database or else select a radio button to opt out of their email being submitted, alongside some other user data.
To achieve this, I have written an if/else statement, however my current code isn't working, and I can't quite work out the correct syntax that I should be using. If the user selects the radio-button, I would like "Email unavailable" to be inserted into the database, else the user-inputted email is inserted. All help appreciated!
Note, my code worked fine until I added the radio-button "no email" option.
HTML file:
<form id="newStaff" method="POST" action="staffportal.php" enctype="multipart/form-data">
<b><i class="fas fa-user-alt"></i> Full name:</b>
<input class="form-control" type="text" id="staffName" name="myStaffName" size="40" maxlength="50"/>
//THE RELEVANT CODE
<b><i class="fas fa-paper-plane"></i> Email:</b>
<div class="form-group row">
<div class="col-xs-4">
<input class="form-control" type="text" id="staffEmail" name="myStaffEmail" size="40"/>
<br>
<input class="form-check-input" type="radio" name="myStaffNoEmail" id="staffNoEmail" value="option1">
<label class="form-check-label" for="gridRadios1">
No available email
</label>
</div>
</div>
<hr>
<b>Job title(s):</b>
<input class="form-control" type="text" id="staffJob" name="myStaffJob" size="40" maxlength="60"/>
<b>Personal bio:</b>
<textarea class="form-control summernote" rows='6' cols='70' id="staffBio" name="myStaffBio" maxlength='1500'></textarea>
<b>Profile photo:</b>
<input type="file" class="custom-file-input" name="myStaffPhoto" id="staffPhoto">
<button name="newStaffBtn" id="newStaffButton" onclick="return confirm('Create new profile?');" type="submit" class="btn btn-primary">Create Profile></button>
</form>
PHP file:
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
$staffNoEmail = mysqli_real_escape_string($conn, $_POST["myStaffNoEmail"]);
//Staff email option
if (!empty($staffNoEmail)){
$staffEmail = "Email unavailable";
} else {
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
If radio input is checked, it will send value with post, if it is not checked it will not send any value and it will not exist in your $_POST array.In your case, you should be checking if it is set.
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
//Staff email option
if (isset($_POST["myStaffNoEmail"])){
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
} else {
$staffEmail = "Email unavailable";
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}

PDO not inputting form data into database

I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.

Update Query PHP - wiping rather than updating

This is for an assignment, so the code is based on how the learning resources are presented. I have a plant database that I have to make changes to, and then update plantID no.2. I have created the form which is then populated with plantID 2 info, but when I click the Update button after making changes, it wipes all the info for that entry in the database. I'm not sure where I have gone wrong. Any help would be awesome.
<?php
// MySQL Database Connect
require_once("connect.php");
// read the values from the form and store in variables
$botanicName = $_POST['bot_name'];
$commonName = $_POST['comm_name'];
$plantDescription = $_POST['pl_desc'];
$commonUse = $_POST['comm_use'];
$maxHeight = $_POST['m_height'];
$maxWidth = $_POST['m_width'];
$popular = $_POST['pop'];
// escape variables for security
$botanicName = mysqli_real_escape_string($conn, $bot_name);
$commonName = mysqli_real_escape_string($conn, $comm_name);
$plantDescription = mysqli_real_escape_string($conn, $pl_desc);
$commonUse = mysqli_real_escape_string($conn, $comm_use);
$maxHeight = mysqli_real_escape_string($conn, $m_height);
$maxWidth = mysqli_real_escape_string($conn, $m_width);
$popular = mysqli_real_escape_string($conn, $pop);
// create the UPDATE query
$query="UPDATE plant SET botanicName='$botanicName', commonName='$commonName', plantDescription='$plantDescription', commonUse='$commonUse', maxHeight='$maxHeight', maxWidth='$maxWidth', popular='$popular' WHERE plantID='2'";
//execute the query
$results = mysqli_query($conn, $query );
// check for errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
exit;
}
else {
// Redirect the browser window back to the make_changes page if there are no errors
header("location: ../make_changes.html");
}
?>
<h2>Edit a Plant</h2>
<?php
// run a select query to return the existing data for the record
$query = "SELECT * FROM plant WHERE plantID='2'";
$results = mysqli_query($conn, $query );
// capture any errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}
else {
// fetch and store the results for later use if no errors
while ($row = mysqli_fetch_array($results)) {
$bot_name = $row['botanicName'];
$comm_name = $row['commonName'];
$pl_desc = $row['plantDescription'];
$comm_use = $row['commonUse'];
$m_height = $row['maxHeight'];
$m_width = $row['maxWidth'];
$pop = $row['popular'];
}
}
?>
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$bot_name?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$comm_name?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$pl_desc?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$m_height?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$m_width?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$pop?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
The parameters sent to $_POST have the name key in your input so your $_POST['bot_name'] for example is empty, the correct way to get that name is $_POST['botanicName'].
This will be your post parameters:
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
The names you use in the form have to exactly match the indexes you use in $_POST. You are using variables that are not defined.
// read the values from the form and store in variables
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
Fix the mysqli escape function calls:
// variable $bot_name does not exist therefore it results in a null value
$botanicName = mysqli_real_escape_string($conn, $bot_name); // bad
// Fixed
$botanicName = mysqli_real_escape_string($conn, $botanicName); // good
Make the form input names the same as $_POST
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$botanicName?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$botanicName?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$plantDescription?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$maxHeight?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$maxWidth?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$popular?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
I needed to change the indexes in the $_POST (I was using undefined variables) and change them also in the mysqli escape functions.

I'm trying to insert SQL query but nothing inserting in database

I'm trying to do simple script with PHP and insert some data, but nothing happens! I knew that I missed something but what is it?
This my code:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="dddd";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
//====== Get Variable======= //
if($_POST['submit-comment']) {
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
And this it the form and the "action" ..
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select>
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
So what I missed please?
Check this working code. Also you had not set element name for Drop down as select_style. It was throwing error for that too.
PHP Code
if(isset($_POST['submit-comment']) && $_POST['submit-comment']!='') {
$host= "localhost";
$user="root";
$pass="";
$db="test";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== Get Variable======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if($name && $email && $content == true) {
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
echo $success;
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
echo $error;
}
mysqli_close($con);
}
HTML
<form method="post" action="" id="form-contact" class="clearfix">
<div id="form-left">
<label for="text-name">Name *</label><br />
<input type="text" name="name" class="input" id="text-name" /><br />
<label for="text-email">From *</label><br />
<input type="text" name="email" class="input" id="text-email" /><br />
<label for="text-phone">Rate us *</label><br />
<div class="select-style">
<select name="select_style">
<option value="5.0">5.0</option>
<option value="4.5">4.5</option>
<option value="4.0">4.0</option>
<option value="3.5">3.5</option>
<option value="3.0">3.0</option>
<option value="2.5">2.5</option>
<option value="2.0">2.0</option>
<option value="2.0">2.0</option>
<option value="1.5">1.5</option>
<option value="1.0">1.0</option>
</select>
</div>
</div>
<div id="form-right">
<label for="text-comment">Review <span></span></label><br />
<textarea name="content" cols="10" rows="20" class="input textarea" id="text-comment"></textarea><br />
<input type="submit" name="submit-comment" class="button" value="Rate Us" />
</div>
<p id="text-contact">
<br><br><font color="#980303">Please Note *</font> Thate Your Reviews Will Not Published Untill We Check it and sure that the review don't contain Bad words or bad language, and be sure that we will publish all reviews and we accept criticism!
</form>
try to put your get variables inside the if else statement
check if there are datas in POST when done submitting:
if($_POST['submit-comment']) {
$name = $_POST['name'];
$email=$_POST['email'];
$rate=$_POST['select_style'];
$content=$_POST['content'];
$insert="insert into reviews (name,email,rate,content) values ('$name','$email','$rate','$content')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
var_dump($_POST);
}
$con->close();
check for errors:
$check = mysqli_query($con,$insert);
var_dump($check);
if you found one, let me know
Note:
Put your insert query and passed on variables (POST) inside your if statement isset(POST["submit-comment"] to eliminate errors of undefined variables.
You should use mysqli_* prepared statement instead to prevent SQL injections.
Answer:
If you insist on retaining your code, you can use mysqli_real_escape_string() function to fertilize a bit the content of your variables before using it in your query.
Your PHP file should look like this:
<?php
$host= "localhost";
$user="root";
$pass="freedoom19";
$db="cookindoor";
$con = mysqli_connect($host,$user,$pass,$db) or mysql_error();
//====== IF SUBMIT-COMMENT ======= //
if(isset($_POST['submit-comment'])) {
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["content"])) {
//====== GET VARIABLES ======= //
$name = mysqli_real_escape_string($con,$_POST['name']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$rate = mysqli_real_escape_string($con,$_POST['select_style']);
$content = mysqli_real_escape_string($con,$_POST['content']);
$insert="INSERT INTO reviews (name,email,rate,content) VALUES ('$name','$email','$rate','$content')";
mysqli_query($con,$insert);
$success = "<span class='success_testmonial'>Thank You! .. Your Raiting Has Been Submitted And We Will Post It As Soon We Verify It !</span>";
}
else {
$error = "<span class='error_testmonial'>Error : one or some fields has left empty .. Please fill all field and try again.</span>";
}
}
mysqli_close($con);
?>
Recommendation:
But if you execute it in mysqli_* prepared statement, your insert query would look like this. Though this is just a simple example but still executable:
if($stmt = $con->prepare("INSERT INTO reviews (name, email, rate, content) VALUES (?,?,?,?)")){ /* CHECK THE QUERY */
$stmt->bind_param('ssss', $_POST["name"], $_POST["email"], $_POST["rate"], $_POST["content"]); /* BIND VARIABLES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE YOUR QUERY */
$stmt->close(); /* CLOSE YOUR QUERY */
}

Categories