Conversion issue after MySQL query - php

What is the problem with my code I can make it work but the error Notice: Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\PHP\index.php on line 50 is appearing above.
The real problem is if I make if($check_email > 0){ to if($check_email_row > 0){ I can't make the error message "Email is already registered" to show below the email textbox and adding the same existing email.
<?php
include("connection.php");
$name = $address = $email = $password = $cpassword = "";
$nameErr = $addressErr = $emailErr = $passwordErr = $cpasswordErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])){
$nameErr = "Name is required!";
}
else{
$name = $_POST["name"];
}
if(empty($_POST["address"])){
$addressErr = "address is required!";
}
else{
$address = $_POST["address"];
}
if(empty($_POST["email"])){
$emailErr = "email is required!";
}
else{
$email = $_POST["email"];
}
if(empty($_POST["password"])){
$passwordErr = "Password is required!";
}
else{
$password = $_POST["password"];
}
if(empty($_POST["cpassword"])){
$cpasswordErr = "Confirm Password is required!";
}
else{
$cpassword = $_POST["cpassword"];
}
if($name && $address && $email && $password && $cpassword){
$check_email = mysqli_query($connections,"SELECT email FROM mytbl WHERE email='$email'");
$check_email_row = mysqli_num_rows($check_email);
if($check_email > 0){
$emailErr = "Email is already registered!";
}else{
$query = mysqli_query($connections, "INSERT INTO mytbl (name,address,email,password,account_type)
VALUES ('$name','$address','$email','$cpassword','2')");
echo "<script language='javascript'>alert('New Record Has Been Added!')</script>";
echo "<script>window.location.href='index.php';</script>";
}
}
}
?>
<style>
.error{
color:red;
}
</style>
<?php include("nav.php");?>
<br>
<br>
<form method="POST" action="<?php htmlspecialchars("PHP_SELF"); ?>">
Name:<input type="text" name="name" value="<?php echo $name; ?>"> <br>
<span class="error"><?php echo $nameErr; ?></span><br>
Address:<input type="text" name="address" value="<?php echo $address; ?>"> <br>
<span class="error"><?php echo $addressErr; ?></span><br>
Email:<input type="text" name="email" value="<?php echo $email; ?>"> <br>
<span class="error"><?php echo $emailErr; ?></span><br>
Password:<input type="password" name="password" value="<?php echo $password; ?>"> <br>
<span class="error"><?php echo $passwordErr; ?></span><br>
Confirm Password:<input type="password" name="cpassword" value="<?php echo $cpassword; ?>"> <br>
<span class="error"><?php echo $cpasswordErr; ?></span><br>
<input type="submit" value="Submit">
</form>
<hr>
<?php
$view_query = mysqli_query($connections, "SELECT * FROM mytbl");
echo "<table border='1' width='50%'>";
echo "<tr>
<td>Name</td>
<td>Address</td>
<td>Email</td>
<td>Option</td>
</tr>";
while($row = mysqli_fetch_assoc($view_query)){
$user_id = $row["id"];
$db_name = $row["name"];
$db_address = $row["address"];
$db_email = $row["email"];
echo "<tr>
<td>$db_name</td>
<td>$db_address</td>
<td>$db_email</td>
<td>
<a href='Edit.php?id=$user_id'>Update</a>
<a href='ConfirmDelete.php?id=$user_id'>Delete</a>
</td>
</tr>";
}
echo"</table>";
?>
<hr>
<?php
$names = array("ian","Joshua","vinoya");
foreach($names as $display_names) {
echo $display_names . "<br>";
}
?>

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.

Login surface does not see the new JSON datas

I have got the following problem. It is a simple login and reg surface.
Register:
<form method="post">
Username :
<input type="text" name="username" placeholder="Username">
<br>
E-mail :
<input type="text" name="email" placeholder="E-mail ">
<br>
Password :
<input type="password" name="password" placeholder="Password">
<br>
<?php
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['username'])) {
$allDatas = json_decode(file_get_contents('data.json'), true);
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$foundUser = false;
$valid = false;
//check the values
if (empty($_POST["email"])) {
?> <font size="1px"><?php echo "Email is required !"; ?> </font><?php
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
?> <font size="1px"><?php echo "Invalid email format!"; ?> </font><?php
}
}
if (empty($_POST["password"])) {
?> <br><font size="1px"><?php echo "Password is required !"; ?> </font><?php
}
if (empty($_POST["username"])) {
?> <br><font size="1px"><?php echo "Username is required !"; ?> </font><?php
}
//is it exists
foreach ($allDatas as $value) {
if ($value[0] == $username) {
?> <br><font size="1px"><?php echo "Username exists!"; ?> </font><?php
$foundUser = true;
break;
} elseif ($value[2] == $email) {
?> <br><font size="1px"><?php echo "E-Mail registered!";?> </font><br><?php
$foundUser = true;
break;
}
}
//add to database
if(!empty($_POST["password"]) && !empty($_POST["username"])&& !empty($_POST["email"]) && filter_var($email, FILTER_VALIDATE_EMAIL)){$valid = true;}
if (!$foundUser && $valid) {
$allDatas[] = array($username, $email, $password);
file_put_contents('data.json', json_encode($allDatas));
echo "Done";
}
unset($allDatas);
}
?>
<br>
<input type="submit" value="Registration">
</form>
<br>
<form action="index.php">
<input type="submit" name="back" value="Back">
</form>
and the login:
<form method="post">
Email:
<input type="text" name="email" placeholder="Email">
<br>
Password:
<input type="password" name="password" placeholder="Password">
<br>
<?php
$allDatas = json_decode(file_get_contents('data.json'), true);
$foundUser = false;
$action = "login.php";
if (isset($_POST['email']) && isset($_POST['password']) ) {
$password = $_POST['password'];
$email = $_POST["email"];
if (empty($_POST["email"])) {
?> <font size="1px"><?php echo "Email is required !"; ?> </font><?php
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
?> <font size="1px"><?php echo "Invalid email format!"; ?> </font><?php
}
}
if (empty($_POST["password"])) {
?> <br><font size="1px"><?php echo "Password is required !"; ?> </font><?php
}
foreach ($allDatas as $value) {
if ($value[2] == $email && $value[1] == $password) {
$foundUser = true;
$username = $value[0];
?> <font size="1px"><?php echo "Success! Welcome ", $username, " !"; ?> </font><?php
$action = "reddragon.html";
}
}
}
if(!$foundUser)
{
?><br> <font size="1px"><?php echo "Please type your datas!"; ?> </font><?php
}
?>
<br>
<input type="submit" value="Log in">
<br>
</form>
<font color="red" size="1px">Before you play, LOG IN!</font>
<form action="<?php echo "$action";?>">
<input type="submit" name="play" value="Play">
</form>
<form action="index.php">
<input type="submit" name="back" value="Back">
</form>
My problem is that, when I add a new member (username, psw, mail), it will be added to the JSON database, but the login surface does not see it! The old ones are ok, but the new one, that I've created by registration is not accepted by the login.
What can be the solution?
flip $email and $password on line #54 of register.php as follows:
$allDatas[] = array($username, $password, $email);

PHP ignoring if statements

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.

PHP How to submit form, if there are no errors. no javascript

I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email 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["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}

Categories