Using array with prepaired statment php, mysql, skip over empty strings - 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.

Related

Optimised PHP code for multiple input check

There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.
Below is my source code:
if(isset($_POST['btnClick']) {
$f_name = NULL;
$l_name = NULL;
$username = NULL;
$email = NULL;
$gender = NULL;
$dob = NULL;
$f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
$l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
$dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);
try {
if(isset($username) && $username != $_SESSION['username']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "Username changed value inputted";
}
else if(isset($email) && $email != $_SESSION['email']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "email change value inputted";
}
else if(isset($username) && isset($email)) {
/*Update both records */
}
You can do something like this:
<?php
try {
if (isset($username) && $username != $_SESSION['username']) {
$fieldsToUpdate[] = 'username=:username';
$updatedFields[] = 'Username';
}
if (isset($email) && $email != $_SESSION['email']) {
$fieldsToUpdate[] = 'email=:email';
$updatedFields[] = 'Email';
}
if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
$sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
/*Update code here...*/
$finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
}
}
PS: This is an example code that how can you optimize your code with PHP arrays and implode() function to run single query to update single or multiple fields.

php prepared statements and proper use

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');
}
?>

String data conversion: Inserting data from Spinner using mysql

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);
}

HTTP Error 500 while inserting data to Database

I have the error mentioned in the title. It occurs when I click the submit button on the form. Here is my form handle file (I don't think that its necessary to copy the form codes):
<?php
$servername = "localhost";
$username = "sabashel_sabaadm";
$password = "saba1365%karaj#*";
$dbname = "sabashel_saba";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fname = $lname = $gender = $birthdate = $organization = $degree = $field = $address = $post_code = $mobile = $email = $check_1 = $check_2 = $check_3 = $check_4 = $check_5 = $check_6 = $check_7 = $check_8 "";
$check_9 = $check_10 = $check_11 = $check_12 = $check_13 = $description = $person_image = "";
if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['gender']) && isset($_POST['birthdate']) && isset($_POST['degree']) && isset($_POST['filed-of-study']) && isset($_POST['address']) && isset($_POST['post-code']) && isset($_POST['mobile']) && isset($_POST['email']) && isset($_POST['check-1']) && isset($_POST['check-2']) && isset($_POST['check-3']) && isset($_POST['check-4']) && isset($_POST['check-5']) && isset($_POST['check-6']) && isset($_POST['check-7']) && isset($_POST['check-8']) && isset($_POST['check-9']) && isset($_POST['check-10']) && isset($_POST['check-11']) && isset($_POST['check-12']) && isset($_POST['check-13']) && isset($_POST['description']) && isset($_POST['person-iamge'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$birthdate = $_POST['birdthdate'];
$organization = $_POST['organization'];
$degree = $_POST['degree'];
$field = $_POST['field-of-study'];
$address = $_POST['address'];
$post_code = $_POST['post-code'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$check_1 = $_POST['check-1'];
$check_2 = $_POST['check-2'];
$check_3 = $_POST['check-3'];
$check_4 = $_POST['check-4'];
$check_5 = $_POST['check-5'];
$check_6 = $_POST['check-6'];
$check_7 = $_POST['check-7'];
$check_8 = $_POST['check-8'];
$check_9 = $_POST['check-9'];
$check_10 = $_POST['check-10'];
$check_11 = $_POST['check-11'];
$check_12 = $_POST['check-12'];
$check_13 = $_POST['check-13'];
$description = $_POST['description'];
$person_image = $_POST['person-image'];
$iftest = true;
}
if ($iftest == true) {
$query = "INSERT INTO volunteer (fname, lname, gender, organization, degree, field, address, post_code, mobile, email, check_1, check_2, check_3, check_4, check_5, check_6, check_7, check_8, check_9, check_10, check_11, check_12, check_13, description, person_image, birthdate) VALUES ('$fname', '$lname', '$gender', '$organization', '$degree', '$field', '$address', '$post_code', '$mobile', '$email', '$check_1', '$check_2', '$check_3', '$check_4', '$check_5', '$check_6', '$check_7', '$check_8', '$check_9', '$check_10', '$check_11', '$check_12', '$check_13', '$description', '$person_image', '$birthdate')";
}
$result = mysqli_query($conn, $query);
if ($result) {
header('Location: http://sabashelter.com/success');
}
else {
header('Location: http://sabashelter.com/fail');
}
}
$conn->close();
?>
And to mention: I have the same exact problem with another page which does the same thing and tries to add a lot of values into the database using the same code. I'm wondering if the problem in this page solves, the same method can be done to the other page as well.
As #CBroe rightly says, check your log files first. It would appear that you are missing an = on line 14.
$fname = $lname = $gender = $birthdate = $organization = $degree = $field = $address = $post_code = $mobile = $email = $check_1 = $check_2 = $check_3 = $check_4 = $check_5 = $check_6 = $check_7 = $check_8 = "";
Furthermore, you have a stray } on line 60.
Your error log file will help you resolve these issues.

PHP error posting form data to database

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....

Categories