I have a form which submits to a php file which inserts data to a table in MySQL there a some fields in this form which may not be filled in and if this is the case the record doesn't get inserted even though I have set the field in MySQL to accept nulls
My Code
<?php
session_start();
include "includes/connection.php";
$title = $_POST['inputTitle'];
$firstname = $_POST['inputFirstname'];
$lastname = $_POST['inputLastName'];
$address1 = $_POST['inputAddress1'];
$address2 = $_POST['inputAddress2'];
$city = $_POST['inputCity'];
$county = $_POST['inputCounty'];
$postcode = $_POST['inputPostcode'];
$email = $_POST['inputEmail'];
$homephone = $_POST['inputHomephone'];
$mobilephone = $_POST['inputMobilephone'];
$userid = $_POST['inputUserID'];
if($title == '' || $firstname == '' || $lastname == '' || $address1 == '' || $address2 == '' || $city == '' || $county == '' || $postcode == '' || $email == '' || $homephone == '' || $mobilephone == '' || $userid == ''){
$_SESSION['status'] = 'error';
} else {
mysql_query("INSERT INTO contact
(`id`,`user_id`,`title`,`firstname`,`lastname`,`address1`,`address2`,`city`,`county`,`postcode`,`email`,`homephone`,`mobilephone`)
VALUES(NULL,'$userid','$title','$firstname','$lastname','$address1','$address2','$city','$county','$postcode','$email','$homephone','$mobilephone')") or die(mysql_error());
$_SESSION['status'] = 'success';
}
header("location: contacts.php");
?>
can anyone tell me what I need to change to sort this issue out?
Best
Justin
P.s sorry if the code block is a bit long but I think it is relevant in this question.
You should change your assignement (for the null-able columns), like
$title = empty( $_POST['inputTitle'] )
? 'NULL'
: "'" . mysql_real_escape_string( $_POST['inputTitle'] ) . "'"
;
And in your query you have to remove the quotes around the variables.
Related
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.
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');
}
?>
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....
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.
I need to change the value of the variable $destination to help validate a form. If none of the fields within the form, the page refreshes with the error message displayed, which works. If the fields are all filled in, the the $destination value should change and the message 'it works!' is printed. However, if all fields are filled in and the user submits the form, the message 'it works!' is printed, but the $destination's value is still set to 'this-page'. What am I missing here?
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!$fname OR !$lname OR !$email OR !$phone) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Hope this is academic. There are better ways to approach this. But here:
$destination = '';
$fname = isset($_POST['fname']) ? $_POST['fname'] : null ;
$lname = isset($_POST['lname']) ? $_POST['lname'] : null ;
$phone = isset($_POST['phone']) ? $_POST['phone'] : null ;
$email = isset($_POST['email']) ? $_POST['email'] : null ;
if (empty($fname) || empty($lname) || empty($phone) || empty($email)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
} else {
print 'It works!';
$destination = 'results-page';
}
Someday take a look at some PHP frameworks and how they handle form validation. for example: http://framework.zend.com/manual/1.12/en/zend.form.elements.html Might give you some insight.
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!empty($fname) || !empty($lname) || !empty($email) OR !empty($phone)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Seems like the problems isn't related to the validation part here. You are getting both the print from the else statement and the $destination variable from the if statement? That should be logically impossible. Are you sure you don't have any syntax errors etc. in your code? Is that the exact code you have in your program?