I would like to write a logic for data validation before insert into database. If the data not valid, then it will prompt user errors, but then I facing problem which not the logic that I wish:
(1) Message "Data successfully inserted!" shown even the error checking message was prompt.
(2) Message "Data successfully inserted!" shown even no data was entered in the form then click submit.
How should I change the logic to the one that I wish to have?
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$comp_nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["comp_licensee_name"])) {
$compLicenseeNameError = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
//php code ends here
?>
<html>
<head>
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<div class="maindiv">
<div class="form_div">
<form method="post" action="compReg.php">
<span class="error">* required field.</span>
<br>
<hr/>
<br>
Company Name:<br><input class="input" type="text" name="comp_name" value="">
<span class="error">* <?php echo $comp_nameError;?></span>
<br>
Company Licensee:<br><input class="input" type="text" name="comp_licensee_name" value="">
<span class="error">* <?php echo $compLicenseeNameError;?></span>
<br>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
I'd accumulate the errors into an array, and proceed to the insert part only if it's empty:
$errors = array();
if (empty($_POST["comp_name"])) {
$errors[] = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$errors[] = "Only letters and white space allowed in the computer name";
}
}
if (empty($_POST["comp_licensee_name"])) {
$errors[] = "Company Licensee Name is required";
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
if (!empty($errors)) {
echo "The following errors occurred:<br/>" . implode('<br/>', $errors);
exit();
}
// If we didn't exit, continue to the insertion code
<?php
// Initialize variables to null.
$comp_nameError ="";
$compLicenseeNameError ="";
if(isset($_POST['comp_name'])) {$comp_name= $_POST['comp_name'];}
if(isset($_POST['comp_licensee_name'])) {
$comp_licensee_name= $_POST['comp_licensee_name'];}
//On submitting form below function will execute
if (isset($_POST['submit'])) {
// check boolean variable value
$is_valid = 1;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//-------------------------Form Validation Start---------------------//
if (empty($_POST["comp_name"])) {
$comp_nameError = "Name is required";
} else {
$comp_name = test_input($_POST["comp_name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comp_name)) {
$validation_error = "Only letters and white space allowed";
$is_valid = 0;
}
}
if (empty($_POST["comp_licensee_name"])) {
$validation_error = "Company Licensee Name is required";
$is_valid =0;
} else {
$comp_licensee_name = test_input($_POST["comp_licensee_name"]);
}
//-------------------------Form Validation End---------------------//
// attempt a connection
if($is_valid == 1 ){
$host="host=xx.xx.xx.xx";
$port="port=xxxx";
$dbname="dbname=xxxx";
$credentials="user=xxxxxx password=xxxxxxx";
$dbh = pg_connect("$host $port $dbname $credentials");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "INSERT INTO t_comp(comp_name, comp_licensee_name)VALUES('$comp_name', '$comp_licensee_name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
} else {
echo $validation_error;
die;
}
}
//php code ends here
?>
Related
I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}
Hi am trying to write code that validates in the backend. The code should stop as soon as there is an error. In my case, even if the conditions are satisfied the code stops in the first name validation block itself.
Also I wish to have only backend validation.
Here is the php code clientRegister.php
<?php
require_once("connection.php");
session_start();
// define variables and set to empty values
$clientFirstName = $clientLastName =$clientEmail = $clientPassword =
$clientCPassword = $clientContact = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// First Name Validation
if (empty($_POST["clientFirstName"])) {
die("error: empty field");
} else {
$clientFirstName = test_input($_POST["clientFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
}
// Last Name Validation
if (empty($_POST["clientLastName"])) {
die("error: empty field");
} else {
$clientLastName = test_input($_POST["clientLastName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientLastName)) {
die("Error: Only letters and white space allowed");
}
}
// Email Validation
if (empty($_POST["clientEmail"])) {
die("error: empty field");
} else {
$clientEmail = test_input($_POST["clientEmail"]);
// check if e-mail address is well-formed
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
die("Error: Invalid email format");
}
}
// Password Validation
if (empty($_POST["clientPassword"])) {
die("error: empty field");
}
// Confirm Password Validation
if (empty($_POST["clientCPassword"])) {
die("error: empty field");
}
if ($clientPassword != $clientCPassword) {
die("error: passwords mismatch");
}else{
$hashedClientPassword = password_hash($clientPassword, PASSWORD_DEFAULT);
}
if (empty($_POST["clientContact"])) {
die("error: empty field");
} else {
$clientContact = test_input($_POST["clientContact"]);
// check if number is correct
if (!preg_match("[0-9]",$clientContact)) {
die("error: Only 0-9 allowed");
}
}
$check_email = $conn->query("SELECT clientEmail FROM tbl_clients WHERE
clientEmail='$clientEmail'");
$emailCount=$check_email->num_rows;
if ($emailCount==0) {
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName,
clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
if ($newClient === false){
$result = array();
$result[] = array("status" => "Error");
}else{
echo "Your have been signed up - please now Log In";
$result = array();
$result[] = array("First Name" => $clientFirstName, "Last Name" => $clientLastName, "Email" => $clientEmail, "Password" => $hashedClientPassword, "Contact" => $clientContact, "status" => "success");
}
}else {
echo "Already Exists";
$result = array();
$result[] = array("status" => "Error");
}
echo json_encode($result);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Reg User</h2>
<form method="post" action="clientRegister.php">
<label>
First Name:<input type="text" name="clientFirstName"><br/>
Last Name:<input type="text" name="clientLastName"><br/>
Email:<input type="text" name="clientEmail"><br/>
Password:<input type="password" name="clientPassword"><br/>
Confirm Password:<input type="password" name="clientCPassword"><br/>
Contact:<input type="text" name="clientContact"><br/>
<input type="submit" value="Register" name="submit">
</label>
</form>
</body>
</html>
You have missing pattern delimiters for your preg_match()
Replace your patterns with following sample:
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
With:
if (!preg_match("/[a-zA-Z ]/",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
Also your
($clientPassword != $clientCPassword)
will always return false because you have not assigned new $_POST values to them. And since you have initialized both variables as empty. So (empty != empty) always return false.
So you should compare like this:
($_POST["clientPassword"] != $_POST["clientCPassword"])
Regarding your query, it was not executed
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
Which I think you meant:
$newClient = $conn->query("INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')");
Note: Your queries are vulnerable to sql injection and you should use prepare statement
DEMO:
http://sandbox.onlinephpfunctions.com/code/d435ae025dc9e22b677823ff37712bb712b71e1b
You can test this file:
https://pastebin.com/AgfquEMC
I attempted PHP and MySQL for the first time today following a tutorial, I was told using $MySQL was outdated and told to use $mysqli which I've attempted. I've uploaded my page to my server on ipage but am only getting a white screen. Its likely there's an error in my code, the server runs sql 5.5.32. The thing is I'm not even getting the echo back messages in Internet Explorer.
Edited with a bind / edited with 'db_table to 'db_table' /added form
<?php
//Database Setup
$mysqli_db = new mysqli($db_host,$db_name,$db_username,$db_password);
function webmailSignUp()
{
$webmailFullName = $_POST['webmailFullName'];
$webmailName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if ((!empty($webmailFullName)) or (!empty($webmailName)) or (!empty($webmailExEmail)) or (!empty($webmailPhone)) or (!empty($webmailDOB)))
{
//Check that there is no existing name in the table
if (checkUser($userName) == false)
{
//Adding the person to the Database Query
$query = "INSERT INTO '$db_table'(userFullName,userName,userExEmail,userPhone,userDOB) VALUES(?,?,?,?,?)";
//Binding to Prevent SQL injection
$requery = $mysqli_db->prepare($query);
$requiry->bind_param($webmailFullName,$webmailName,$webmailExEmail,$webmailPhone,$webmailDOB);
if ($requery->execute())
{
echo "Person has been added";
}
else
{
echo "bind failed";
}
}
else
{
echo "There is already a user registered with this username. Please try a different one.";
}
}
else
{
echo "One of your fields are blank! Please try again";
}
}
function checkUser($userNameCheck)
{
//Check the field userName is the same as the Posted Username
$Field = "userName"; //The Field to check
$query = "SELECT '$Field' WHERE '$Field'='$webmailName' FROM '$db_table' LIMIT 1";
$result = mysqli_query($query, $mysqli_db) or die(mysql_error());
if (!$row = mysqli_fetch_array($result) or die(mysql_error()))
{
return false; //username was not found in the field in the table
}
else
{
return true; //username was found in the field in the table
}
}
function close()
{
$mysqli_db->close();
}
//Main Code Sequence
error_reporting(-1);
ini_set('display_errors',1);
if(isset($_POST['webmailRegisterButton']))
{
echo("firstbit");
webmailSignUp();
close();
echo "End of Registration";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
close();
echo "End of Password Reset Request";
}
?>
Form:
<form method="POST" action="../_webmail/mailDB.php">
<div class="popupTitleCell"><h3>Name:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailFullName" class="popupInputField"></div>
<div class="popupSpacer2"><p>Your Full Name (ex. John Coles)</p></div>
<div class="popupTitleCell"><h3>UserName:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailUserName" value="#allcoles.com" class="popupInputField"></div>
<div class="popupSpacer2"><p>Preference email (ex john#allcoles.com)</p></div>
<div class="popupSpacer"><hr></div>
<div class="popupTitleCell"><h3>Existing Email:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailExEmail" class="popupInputField"></div>
<div class="popupSpacer2"><p>REQUIRED to recieve SignIn details</p></div>
<div class="popupTitleCell"><h3>Phone Number:</h3></div>
<div class="popupInputCell"><input type="text" name="webmailPhone" class="popupInputField"></div>
<div class="popupSpacer2"><p>(allows for SMS confirmation)</p></div>
<div class="popupTitleCell"><h3>Date of Birth:</h3></div>
<div class="popupInputCell"><input type="text" id="datepickerRegister" name="webmailDOB"></div>
<div class="popupSpacer2"><p>Select your DOB from the calender</p></div>
<div class="popupSpacer"><hr></div>
<div class="popupButtonCell">
<button type="submit" name="webmailRegisterSubmit" value="register" id="submitButton" class="popupButton">
<span>Register</span></button></div>
</form>
Any help would be appreciated.
Can you also put the code of the form you are using to submit data on this file. Because if you directly open this file no code will be execute. Also please try this
<?php
//Main Code Sequence
error_reporting(-1);
ini_set('display_errors',1);
//Database Setup
$db_host = "localhost";
$db_name = "test";
$db_table = "emailUser";
$db_username = "root";
$db_password = "";
$mysqli_db = new mysqli($db_host,$db_username,$db_password, $db_name);
function webmailSignUp()
{
$webmailFullName = $_POST['webmailFullName'];
$webmailName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if ((!empty($webmailFullName)) or (!empty($webmailName)) or (!empty($webmailExEmail)) or (!empty($webmailPhone)) or (!empty($webmailDOB)))
{
//Check that there is no existing name in the table
if (checkUser($userName) == false)
{
//Adding the person to the Database Query
$query = "INSERT INTO '$db_table(userFullName,userName,userExEmail,userPhone,userDOB) VALUES($webmailFullName,$webmailName,$webmailExEmail,$webmailPhone,$webmailDOB)";
echo "Person has been added";
}
else
{
echo "There is already a user registered with this username. Please try a different one.";
}
}
else
{
echo "One of your fields are blank! Please try again";
}
}
function checkUser($userNameCheck)
{
//Check the field userName is the same as the Posted Username
$Field = "userName"; //The Field to check
$query = "SELECT '$Field' WHERE '$Field'='$webmailName' FROM '$db_table' LIMIT 1";
$result = mysqli_query($query, $mysqli_db) or die(mysql_error());
if (!$row = mysqli_fetch_array($result) or die(mysql_error()))
{
return false; //username was not found in the field in the table
}
else
{
return true; //username was found in the field in the table
}
}
function close()
{
$mysqli_db->close();
}
if(isset($_POST['webmailRegisterButton']))
{
echo("firstbit");
webmailSignUp();
close();
echo "End of Registration";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
close();
echo "End of Password Reset Request";
}
?>
I have a basic Form that submits data into a database and I want it to require certain fields to be submitted, so far it recongizes that the fields are empty, but it still submits regardless. I can't seem to find a solution..
Code
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr;
$asin = $quantity = $floor = $location;
# this is processed when the form is submitted
# back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"]))
{$asinErr = "ASIN is required";}
else
{$asin = addslashes($_POST["asin"]);}
if (empty($_POST["quantity"]))
{$qtyErr = "Quantity is required";}
else
{$quantity = addslashes($_POST["quantity"]);}
if (empty($_POST["floor"]))
{$floorErr = "Floor is required";}
else
{$floor = addslashes($_POST["floor"]);}
if (empty($_POST["location"]))
{$locErr = "Location is required";}
else
{$location = addslashes($_POST["location"]);}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', now()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Amnesty Added - View it <a href=amnesty_log_summary.php>HERE</a></font></h3>";
}
?>
<form name="fa" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<table>
<tr><td>ASIN:</td><td><input type="text" name="asin" id="asin"><span class="error">* <?php echo $asinErr;?></span></td></tr>
<tr><td>Quantity:</td><td><input type="text" name="quantity" id="quantity"><span class="error">* <?php echo $qtyErr;?></span></td></tr>
<tr><td>Floor:</td><td><select name="floor"><option value="1">Floor 1</option><option value="2">Floor 2</option></select><span class="error">* <?php echo $floorErr;?></span></td></tr>
<tr><td>KIVA Floor:</td><td><input type="radio" value="Yes" name="location">Yes<input type="radio" value="No" name="location">No</select><span class="error">* <?php echo $locErr;?></span></td></tr>
<tr><td><input type="submit" name="submit" id="submit" value="Submit Amnesty!"></td></tr>
</table>
</form>
Updated:
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr = "";
$asin = $quantity = $floor = $location = "";
$lb_error = 0;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
if (empty($_POST["quantity"])) {
$qtyErr = "Quantity is required";
$lb_error = 1;
} else {
$quantity = addslashes($_POST["quantity"]);
}
if (empty($_POST["floor"])) {
$floorErr = "Floor is required";
$lb_error = 1;
} else {
$floor = addslashes($_POST["floor"]);
}
if (empty($_POST["location"])) {
$locErr = "Location is required";
$lb_error = 1;
} else {
$location = addslashes($_POST["location"]);
}
if($lb_error) {
continue;
}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', curdate()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
You want to check if you error variables are empty. If they are not, then break the script
ie
if(!empty($asinErr) || !empty($qtyErr) || !empty($floorErr) || !empty($locErr) ) {
break;
}
Something along these lines.
Check for the errors before you get to the point where you are writing to the database
Define at the top
$lb_error = 0;
Throughout your if/else checks for errors, if there is an error, assign the variable a 1
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
Then after you have completed all of these, do a check for errors and break if there are any
if($lb_error) {
break;
}
I have heard of this issue but can't seem to figure it out. I have the database and table names correct. I am not finding any errors and i even inserted a table myself on phpmyadmin that worked but when I tried to do it on my site it doesnt work. I even tested the connection..Not sure what to do now
Maybe someone can take a look at my code and see if they notice anything
<?php
if(mysql_connect('<db>', '<un>', '<pw>') && mysql_select_db('smiles'))
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
$insert = "INSERT INTO 'guestbook'VALUES('','$time','$guestbook_name','$guestbook_message')";
if($insert = mysql_query($insert)){
header('Location: '.$_SERVER['PHP_SELF']);
} else{
$errors[] = 'Something went wrong . Please try again.';
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
else {
'Fixing idiot';
}
?>
<hr />
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST">
<p>Post Somethign</p>
<br />
Name:<br /><input type="text" name="guestbook_name" maxlength="25" />
<br />
Message:
<br />
<textarea name="guestbook_message" rows="6" coles="30"maxlength="255"></textarea>
<input type="submit" value="Post" />
</form>
Remove quotes from table name 'guestbook' and leave a space between it and values
Table name doesn't need quotes and supossing you're using id autoincrement, don't insert an empty string. So it should be:
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
Also, take a look at your $time value. What MySQL data type is?
After the insert, try to display the mysql error:
$conn = mysql_connect('<db>', '<un>', '<pw>');
mysql_query($insert)
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
EDIT: The hole snippet should be similar to:
<?php
$conn = mysql_connect('<db>', '<un>', '<pw>')
if( $conn && mysql_select_db('smiles')) //Note $conn
{
$time = time();
$errors = array();
if(isset($_POST['guestbook_name'], $_POST['guestbook_message'])){
$guestbook_name = mysql_real_escape_string(htmlentities($_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities($_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All Fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>255) {
$errors[] = 'One or more fields exceed the character limit.';
}
if (empty($errors)) {
mysql_query($insert)
$insert = "INSERT INTO guestbook VALUES('$time','$guestbook_name','$guestbook_message')";
if (mysql_errno($conn)){
$errors[] = mysql_error($conn);
}else{
header('Location: '.$_SERVER['PHP_SELF']);
}
} else {
foreach($errors as $error) {
echo '<p>'.$error.'</p>';
}
}
}
//display entries
}
you can try below query for insertion:
$insert = "INSERT INTO guestbook VALUES('','{$time}','{$guestbook_name}','{$guestbook_message}')";