PHP ignoring if statements - php

I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>

You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE

You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.

Related

Using Parameterized Queries/Prepared Statements

I'm new to php coding and have been told by others that I need to be using parameterized queries/prepared statements for my php scripts and MySQL database. I've looked at other examples of scripting these prepared statements and they usually refer to user login functions. My query is just a web form to capture user inputted data and store in database (SQL insert as opposed to SQL select). I am hoping someone can help me with how to script the php to prevent sql injections. Also hoping someone can let me know whether these prepared statements should also be used in php SQL Select scripts where I am only displaying database records on a form. Thanks in advance!
Here are the two php files I am using, the first is my database connection script:
<?php
DEFINE ('DB_USER', 'fakeuser');
DEFINE ("DB_PSWD", 'fakepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'newspaper');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
Web form PHP script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die(mysqli_error($dbcon)); //and die('error inserting new record') ;
} // end of nested if statement
// else
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
UPDATED CODE with Prepared Statement 9/3/17: See bottom of script (Please tell me if you see any issues with this) Also I've commented out the !mysqli_query IF statement below the prepared statement as I thought this was now redundent, but please tell me if it is still required.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?,?,?,?)";
$stmt = mysqli_stmt_init($dbcon);
if (!mysqli_stmt_prepare($stmt,$sqlinsert)) {
echo "SQL error"; }
else {
mysqli_stmt_bind_param($stmt,"ssss",$fname, $femail, $fcomment, $fsubsciption);
mysqli_stmt_execute($stmt);
echo '1 record added to the database';
//if (!mysqli_query($dbcon, $sqlinsert)) {
//die(mysqli_error($dbcon));
} // end of nested IF statement
// else
//$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>

Defined Variable in PHP script has undefined variable error

I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.

PHP code not working (Not inserting data into database)

I am trying to process a form which will insert data into database, but it is inserting anything in database. I am trying this since couple of days...but got no solution....it is also not showing any error also..please guide....asap...
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
This code is also not showing any error....so that's why I can't tell you what's wrong here......but it's not working...that's all I can say right now....Thank You...:)
Hello everyone once again, thanks for your suggestion, but it didn't work for me....but when I put
if(!empty($errors)){
instead of
if(empty($errors)){
it works....it should not work, right?...because it will take any data and insert it into database..if not please guide me....Thank you to all...:)
You cant use set a session after starting printing to browser.
so move
if(isset($_POST['submit'])){
to the top of page, before the HTML.
It shows a debug error message like follows.
Fatal error: Call to undefined function navigation() in /var/www/poc.php on line 25
It mean the function navigation() is used but not created any where in the script. And fatal error won't let the script to further proceed. So it is a blocking point
At least include following line at top of PHP block will avoid the error
<?php
function navigation(){
return 1;
}
?>
Additionally if you want to see the error message on your server use following two lines on the top of the script.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>

Validating email before sending it from validated PHP form

I'm using this code from W3 (http://www.w3schools.com/php/php_form_complete.asp) to make server side validation for given example form.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Although server side validation works fine,I can't put mail() function to work ONLY WHEN both $name (treated as subject) and $comment (treated as message) fields are filled.
I've tried many combinations but email is always submitted even when fields are empty.
So my question is: how to make this validated form send email only when $name and $comment fields are filled and validated?
As you are creating $nameErr when the name is invalid and $comment is an empty string when the comment is valid you can use the following conditional:
if (!$nameErr && $comment) {
}
Empty strings are considered FALSE:
http://php.net/manual/en/language.types.boolean.php
You can always use flags.
<?php
....
// let's say there are some flags for validation
if($flag1 && $flag2 && .. $flagN){
// perform email sending here
}
?>
Or you can use the default error message variables; check if they are empty
<?php
if(!empty($nameErr) && !empty($comment)){
// perform email sending
}
?>
Do the validation after you validated $name and $comment:
if($nameErr == "" && $emailErr == "") { // If they are empty, no errors where found
// Do your email validation here
}

PHP Form submitting to MySQL whether validation conditions are met or not

My php self-validating form is submitting to sql database whether the characters entered into form fields are appropriate or not...How do stop it from submitting until the conditions for each form field are met?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
<script>
// $(function () {
// $('form').on('submit', function (e) {
// $.ajax({
// type: 'post',
// url: 'contact.php',
// data: $('form').serialize(),
// success: function () {
// alert('Thank you! your form has been submitted');
// }
// });
// e.preventDefault();
// });
// });
</script>
</head>
<body>
<div id="contactuscall">
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = "";
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{$firstnameErr = "A first name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed";}
}
//check if a last name was provided
if (empty($_POST["lastname"]))
{$lastnameErr = "A last name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "Only letters and white space allowed";
}
}
// check if an email was provided
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["cellphone"]))
{$cellphoneErr = "Please provide a phone number";}
else {
$cellphone = test_input($_POST["cellphone"]);
// Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
{$cellphoneErr = "Invalid format";}
}
if (empty($_POST["dogname"]))
{$dognameErr = "A doggy name is required";}
else {
$dogname = test_input($_POST["dogname"]);
// check if dogname only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
{$dognameErr = "Only letters and white space allowed";}
}
if (empty($_POST["Breed"]))
{$BreedErr = "A breed name is required";}
else {
$Breed = test_input($_POST["Breed"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
{$BreedErr = "Only letters and white space allowed";}
}
if(empty($_POST['genDer']))
{$genDerErr= "You forgot to select a Gender!";}
else {
$genDer=($_POST['genDer']);
}
//make sure one of the services requested checkboxes are checked
$reasoN = $_POST['reasoN'];
if(empty($reasoN))
{
$reasonErr="You didn't select any services.";
}
else
{
$N = count($reasoN);
$reasonErr="You selected $N services(s): ";
}
// if comment section is not empty then run test_input function to purge possible malicious code
if (empty($_POST["freecomments"]))
{$freecomments = "";}
else
{$freecomments = test_input($_POST["freecomments"]);}
}
$host="fdb3.biz.nf"; //localhost
$dbuser="1546259_rsginfo"; //user
$dbpass="RSGnow12"; //pass
$dbname="1546259_rsginfo"; //db name
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn)
?>
<form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<hr />
First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>">
<span class="error">* <?php echo $firstnameErr;?></span>
E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br />
Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>">
<span class="error">* <?php echo $lastnameErr;?></span>
Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>">
<span class="error">* <?php echo $cellphoneErr;?></span><br />
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<hr />
Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span>
Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span>
<p>
Gender:<select name="genDer" class="textfield">
<option value="">--</option>
<option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option>
<option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option>
<option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option>
<option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option>
</select><span class="error">* <?php echo $genDerErr;?></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<hr />
<input type="checkbox" name="reasoN[]" value="walkSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoN[]" value="RawSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!
<input type="checkbox" name="reasoN[]" value="groomSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer!
<span class="error">* <?php echo $reasonErr;?></span>
<?php echo $reasonConfirm;?>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Comments & Questions</legend>
<hr />
<textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea>
</fieldset>
<input id="submit" type="submit" name="submit" value="submit">
</form>
</div>
<?php
echo "<h2>Your Input:</h2>";
echo $firstname;
echo "<br>";
echo $lastname;
echo "<br>";
echo $email;
echo "<br>";
echo $cellphone;
echo "<br>";
echo $dogname;
echo "<br>";
echo $Breed;
echo "<br>";
echo $genDer;
echo "<br>";
echo $reasoN;
echo "<br>";
echo $freecomments;
?>
</body>
</html>
Your code actually tries to insert values in to the table whether or not the validation is successful. The easiest and the quickest solution for this is to use a boolean flag.
eg:
// ...
$formValid = true; // Define a boolean and set to true before validating
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{
$firstnameErr = "A first name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "Only letters and white space allowed";
$formValid = false; // Invalid input - set the flag to false
}
}
}
// ....
// Eventually wrap the mysql logic inside a condition
if ($formValid)
{
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn);
}
// ... rest of your code

Categories