I was told that I am not properly using prepared statements.. though my understanding of the subject was that using prepared statements required a simple step by step procedure such as prepare,bind,fetch.. I was also told that this would send the data at separate times to make querying user input to the data base more secure. Here is an example of how I am using using prepared statements if someone could comment as to if it is correct and safe that would be greatly appreciated. Additional information is always welcome.
<?php
//define connection
$conn = new mysqli('localhost', 'over_watch','xxxxxxx','billing');
//create variales and check if form is submitted
$first = htmlentities($_POST['first']);
$last= htmlentities($_POST['last']);
$address = htmlentities($_POST['address']);
$addressTwo = htmlentities($_POST['addressTwo']);
$city = htmlentities($_POST['city']);
$zip = htmlentities($_POST['zip']);
$state= htmlentities($_POST['state']);
$email = htmlentities($_POST['email']);
$password = htmlentities($_POST['password']);
$confirmPassword = htmlentities($_POST['confirmPassword']);
//EmailConfirmation
$CheckEmailSQL = $conn->prepare( "SELECT email FROM members WHERE email = ?;");
$CheckEmailSQL->bind_param('s',$email);
$CheckEmailSQL->execute();
$CheckEmailSQL->store_result();
$CheckEmailSQL->bind_result($CheckEmail);
$CheckEmailSQL->fetch();
//$CheckEmailSQLQuery = mysqli_query($conn,$CheckEmailSQL);
$CheckIfEmailExists = $CheckEmailSQL->num_rows();
//RegExExpressionsPassword//Email//ZipCode
$PasswordRegEx="/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\`\~\!\#\#\$\%\^\&\*\(\)\-\_\=\+\[\]\{\}\\\|\;\:\,\.\<\>\/\?\'\"]).*$/";
$ZipCodeRegEx='/^\d{5,10}$/';
$EmailRegEx='/^.+#.+\.[a-zA-Z]{2,4}$/';
//ConditionalStatementsToCheckIfFormIsProperlyFilledOut
if (empty($first) || empty($last) || empty($address) || empty($addressTwo) || empty($city) || empty($zip)|| empty($state) || empty($email) || empty($password)|| empty($password) ||empty($confirmPassword)){
header('Location:http://localhost/xampp/Websites/subWeb/sign-in-required-fill-out.php');
}
//CheckForValidZipCode
elseif(!(preg_match($ZipCodeRegEx,$zip))){
echo 'invalid';
}
//CheckIfEmailExists
elseif( $CheckIfEmailExists > 0 or !(preg_match($EmailRegEx,$email))){
header('Location:http://localhost/xampp/Websites/subWeb/sign-in-required-fill-out-email.php');
}
//CheckIfValidEmailisUsed
elseif(!(preg_match($PasswordRegEx,$password)) or $password !== $confirmPassword ){
header('Location:http://localhost/xampp/Websites/subWeb/sign-in-required-fill-out-password.php');
}
//QueryResultsToDataBase
else{
//HashPasswords
$passwordHashed = password_hash($password,PASSWORD_BCRYPT );
$confirmPasswordHashed = password_hash($confirmPassword,PASSWORD_BCRYPT );
//Query DataBase
$SQLInsertFormDataIntoDataBase = $conn->prepare("INSERT INTO members(first,last,address,address_two,city,zip,state,email,password,confirm_password)
VALUES (?,?,?,?,?,?,?,?,?,?);");
$SQLInsertFormDataIntoDataBase->bind_param('sssssissss',$first,$last,$address,$addressTwo,$city,$zip,$state,$email,$passwordHashed,$confirmPasswordHashed);
$SQLInsertFormDataIntoDataBase->execute();
header('Location:../Login.php');
}
?>
Related
I am trying to add data into MySQL database through spinner that has several options to choose. I do not know how to state value from spinner into MySQL code. The error occurs on the 39th line, which first line of Inserting Into database using MySQL code. I look forward to hearing from you soon.
<?php
include 'db.php';
$user_type = ['user_type'];
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if(/*$user_type == '' ||*/ $first == '' || $last == '' || $email == '' || $username == '' || $password == '' || $phone == '')
{
echo 'Please, fill all fields';
} else{
$sql = "SELECT * FROM users WHERE user_username='$username'";
$check = mysqli_fetch_array(mysqli_query($conn,$sql));
if(isset($check))
{
echo 'Username already exist. Please, use another one.';
}else{
$hashedPWD = password_hash($password , PASSWORD_DEFAULT); //hash password
$sql = "INSERT INTO users (user_type, user_first, user_last, user_email, user_username, user_pwd, user_phonenumber) VALUES('$user_type','$first','$last','$email','$username','$hashedPWD','$phone')";
if(mysqli_query($conn,$sql))
{
echo 'Successfully registered';
} else{
echo 'Oops! Please try again!';
}
}
mysqli_close($conn);
}
I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....
When I run this page, everything shows up correctly, but then when I try to test my various error messages, my button keeps redirecting me back to my login page as if everything was inputted correctly. It fails to register the if blocks I've included. Below is the php (the html runs fine, not included).
*Side note, a few lines are commented out because I initially had PDO and am changing them over to mysql, but those shouldn't affect everything else running. I have them commented out too so if things did work, I wasn't adding unnecessary info to my database.
Of course, PHP is not skipping anything. It is diligently running your conditions, but in your code the only condition that affects the insert is the last one.
To make it work as desired you have to change all your ifs to elseif save for the first one
The problem: Your error may be set, but your INSERT will execute only if $password == $password2 which will be true if they're both empty.
You need to indicate alternative paths by doing else if
<?php
error_reporting (E_ALL);
$error = "";
if (isset($_POST['createAccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$city = $_POST['city'];
$province = $_POST['province'];
$postalCode = $_POST['postalCode'];
if (!$username){
$error = "<br><div><em>No username entered.</em></div>";
}
elseif (!$password || !$password2){
$error = "<br><div><em>Missing password.</em></div>";
}
elseif (!$firstName || !$lastName){
$error = "<br><div><em>Please enter first and last name.</em></div>";
}
elseif (!$address || !$city || !$province || !$postalCode){
$error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
}
elseif ($password != $password2){
$error = "<br><div><em>Passwords do not match.</em></div>";
}
else{
$conn = mysql_connect(<blocked out for privacy reasons>);
$db = mysql_select_db("grocery", $conn);
$account = mysql_query("SELECT *
FROM accounts
WHERE username = '$username'",
$conn);
$rowExist = mysql_num_rows($account);
if ($rowExist == 1){
$error = "<br><div><em>Username already exists.</em></div>";
}
else {
//$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
// VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
//$conn->exec($newAccount);
header("location: GroceryLogin.php");
}
mysql_close($conn);
}
}
// I'm guessing here you do an echo $error;
I have this form and start by checking if the fields are empty and it works pretty well. My question here is: why do i get errors when I want to verify if user exists?
Here is my code:
<?php
require_once '../../includes/database.php';
require '../../includes/functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$repassword = $_POST['re-password'];
$conn = connect($config);
if(empty($username) || empty($password) || empty($repassword)) {
$status = 'Fields must not be empty';
}
$results = $conn->query("SELECT * FROM admin WHERE username = " . $username);
foreach($results as $result) {
print_r($result);
}
}
include 'staff_create.view.php';
You need to enclose username between ' because is a string.
But you should use the potential of prepared statements:
$stmt = $conn->prepare("SELECT * FROM admin WHERE username = ?");
$stmt->execute($username);
$stmt = $stmt->fetchAll(PDO::FETCH_CLASS);
Or
$stmt = $conn->prepare("SELECT * FROM admin WHERE username = :username");
$stmt->execute(array(":username" => $username));
$stmt = $stmt->fetchAll(PDO::FETCH_CLASS);
You will avoid SQL injection writing your querys this way
You also might to check to see if the username is set...
$username="";
if (isset($_POST['username'])) {
$username = $_POST['username'];
}
You are missing the else statement and maybe a hard error after the $status is set...
<?php
require_once '../../includes/database.php';
require '../../includes/functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$repassword = $_POST['re-password'];
$conn = connect($config);
if(empty($username) || empty($password) || empty($repassword)) {
$status = 'Fields must not be empty';
}
else {
$results = $conn->query("SELECT * FROM admin WHERE username = " . $username);
foreach($results as $result) {
print_r($result);
}
}
}
include 'staff_create.view.php';
Having some issues learning prepaired statments for mysql.
I hade everything working then i got a new problem, The initial problem was i wanted to skip over empty strings in a mysql update form (ie: user profile).
I tried to programaticly do it in php, but i dont understand prepaired statments enough to do this, i keep reading but i am having no success can you help me in making this work as intended? Essentialy im trying to use a array in a prepaired statment.
if (empty($email) && empty($fullname) && empty($address) && empty($country) && empty($state) && empty($city) && empty($postcode) && empty($phone) && empty($password) && empty($random_salt)) {
echo "Nothing to do....";
return;
}
else {
$state = $_POST['state'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$fullname = $_POST['fullname'];
$address = $_POST['address'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$merchantID = $_POST['merchantId'];
// The hashed password from the form
$password = $_POST['p'];
$pass2 = $password;
$pass = $_POST['password'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
$updates = array();
if (!empty($email))
$updates[] = 'email="'.$email.'"';
if (!empty($address))
$updates[] = 'address="'.$address.'"';
if (!empty($country))
$updates[] = 'country="'.$country.'"';
if (!empty($state))
$updates[] = 'state="'.$state.'"';
if (!empty($city))
$updates[] = 'city="'.$city.'"';
if (!empty($postcode))
$updates[] = 'postcode="'.$postcode.'"';
if (!empty($phone))
$updates[] = 'phone="'.$phone.'"';
if (!empty($password))
$updates[] = 'password="'.$password.'"';
if (!empty($random_salt))
$updates[] = 'salt="'.$random_salt.'"';
$updates = implode(', ', $updates);
if ($update_stmt = $mysqli->prepare("UPDATE table SET ? WHERE id = ".$merchantID)) {
$update_stmt->execute($updates);
$update_stmt->close();
//
echo '<br><p>';
echo ' Account infomation update was a success...';
}
else {
echo "oppps, update didnt work, please report this to admin";
}
}
Now i think i have strayed, no matter why i try i cant seem to work out how to do this, granted i dont fully understand prepaired statments im trying.