my previously store data are automatically deleted while updating a data - php

I am currently working on a job portal project, where I can store user information,
in my project after registration, user can go there dashboard, and update there remaining form like, education detail and company detail. but after that when user like to update one of the any field in form, it can update that field but it can delete my remaining field, in education detail field or company detail field. What kind of this problem is occurred ?
updateprofile.php
<?php
session_start();
if(empty($_SESSION['id_user']))
{
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if(isset($_POST))
{
//Escape Special Characters
$firstname = $conn->real_escape_string( $_POST['fname']);
$lastname = $conn->real_escape_string($_POST['lname']);
$gender = $conn->real_escape_string($_POST['gender']);
$contactno = $conn->real_escape_string($_POST['contactno']);
$address = $conn->real_escape_string($_POST['address']);
$city = $conn->real_escape_string($_POST['city']);
$state = $conn->real_escape_string($_POST['state']);
$aboutme = $conn->real_escape_string($_POST['aboutme']);
$qualification = $conn->real_escape_string($_POST['qualification']);
$stream = $conn->real_escape_string($_POST['stream']);
$coursetype = $conn->real_escape_string($_POST['coursetype']);
$university = $conn->real_escape_string($_POST['university']);
$passingyear = $conn->real_escape_string($_POST['passingyear']);
$skill = $conn->real_escape_string($_POST['skill']);
$industry = $conn->real_escape_string($_POST['industry']);
$functional_area = $conn->real_escape_string($_POST['functional_area']);
$role = $conn->real_escape_string($_POST['role']);
$is_current_job = $conn->real_escape_string($_POST['is_current_job']);
$startdate = $conn->real_escape_string($_POST['startdate']);
$enddate = $conn->real_escape_string($_POST['enddate']);
$current_compname = $conn->real_escape_string($_POST['current_compname']);
$current_salary = $conn->real_escape_string($_POST['current_salary']);
$designation = $conn->real_escape_string($_POST['designation']);
$notice_period = $conn->real_escape_string($_POST['notice_period']);
$job_desc = $conn->real_escape_string($_POST['job_desc']);
$experience = $conn->real_escape_string($_POST['experience']);
$current_location = $conn->real_escape_string($_POST['current_location']);
$prefer_location = $conn->real_escape_string($_POST['prefer_location']);
$uploadOk = true;
if(is_uploaded_file($_FILES['resume']['tmp_name']))
{
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['resume']['tmp_name']))
{
if($resumeFileType == "pdf")
{
if($_FILES['resume']['size'] < 500000)
{
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
}
else
{
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
}
else
{
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
}
else
{
$uploadOk = false;
}
//Update User Details Query
$sql = "UPDATE user SET firstname='$firstname', lastname='$lastname',gender='$gender',contactno='$contactno', address='$address', city='$city', state='$state',aboutme='$aboutme',qualification='$qualification', stream='$stream',coursetype='$coursetype',university='$university',passingyear='$passingyear',skill='$skill',
industry='$industry',functional_area='$function_area',role='$role',is_current_job='$is_current_job',startdate='$startdate',enddate='$enddate',current_compname='$current_compname',current_salary='$current_salary',designation='$designation',notice_period='$notice_period',job_desc='$job_desc',experience='$experience',current_location='$current_location',prefer_location='$prefer_location'";
if($uploadOk == true)
{
$sql .= ",resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE)
{
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
}
else
{
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
}
else
{
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
image of user table

Using prepared statements and dynamic field mapping to update only those fields which has value in it, here is what your code should look like
<?php
session_start();
if (empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
require_once("../db.php");
if (isset($_POST)) {
$uploadOk = true;
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir . $file;
if (file_exists($_FILES['resume']['tmp_name'])) {
if ($resumeFileType == "pdf") {
if ($_FILES['resume']['size'] < 500000) {
// File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size of file. Max Size Allowed : 5MB";
header("Location: edit_profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format of file only pdf Allowed.";
header("Location: edit_profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$postf2sqlf = array(
'firstname' => 'firstname',
'lastname' => 'lastname',
'gender' => 'gender',
'contactno' => 'contactno',
'address' => 'address',
'city' => 'city',
'state' => 'state',
'aboutme' => 'aboutme',
'qualification' => 'qualification',
'stream' => 'stream',
'coursetype' => 'coursetype',
'university' => 'university',
'passingyear' => 'passingyear',
'skill' => 'skill',
'industry' => 'industry',
'functional_area' => 'function_area',
'role' => 'role',
'is_current_job' => 'is_current_job',
'startdate' => 'startdate',
'enddate' => 'enddate',
'current_compname' => 'current_compname',
'current_salary' => 'current_salary',
'designation' => 'designation',
'notice_period' => 'notice_period',
'job_desc' => 'job_desc',
'experience' => 'experience',
'current_location' => 'current_location',
'prefer_location' => 'prefer_location'
);
$sql = 'UPDATE `user` SET ';
$skipComma = true;
$params = array('');
foreach ($postf2sqlf as $p => $s) {
if (isset($_POST[$p]) && !empty($_POST[$p])) {
$sql .= ($skipComma ? '' : ',') . '`' . $s . '` = ?';
$params[] = &$_POST[$p];
$params[0] .= 's';
$skipComma = false;
}
}
if ($uploadOk == true) {
$sql .= ",resume=?";
$params = &$file;
$params[0] .= 's';
}
$sql .= " WHERE id_user=?";
$params[0] .= 's';
$params[] = &$_SESSION['id_user'];
$stmt = $db->prepare($sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
$res = $stmt->execute();
if ($stmt->errno == 0) {
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
//Close database connection.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit_profile.php");
exit();
}
Explanation
Created $postf2sqlf array, holding the Form fields as index, and sql field names as value.
Iterating over $postf2sqlf and checking if the index is set and not empty in $_POST, started collecting the parameters passing references in $params to use in a prepared statement to avoid SQL Injection. $params[0] holds the type (s => string) of named parameters, as mysqli_statement::bind_param requires this, and as parameters added, another s is concatenated. (For a strict sql, instead of s, other types could be used upon checking their types but for simplicity's sake I used s)
The reason to collect variables by passing references is because `mysqli_statement::bind_param requires the variables pass by references.
call_user_func_array was used to call mysqli_statement::bind_param with the $params with each index being a different argument.
Finally, $stmt->errno was checked against 0 (0 being no errors), to check that it was actually completed correctly.

Related

I cannot upload variables to database

I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.

Condition to Skip Input field if Empty

I'm trying to set a condition wherein if the 'filefield' is empty, it will skip the insert in DB as it is only an option and just proceed in inserting of 'name' and 'description' in the DB, which will never be empty.
<?php
include("connection.php");
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
if ($name == '' || $description == '' )
{
$error = 'ERROR: Please fill required fields!';
renderForm($name, $description);
}
else
{
if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{
echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}
$path=md5(microtime()).'.'.$ext;
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>
I'm not sure how to proceed with the condition. Any help is highly appreciated.
First, close off all of your logic, including if(move_uploaded_file), so that the $query is competely outside of any conditionals. Then it's just a matters of checking whether the filefield was filled out or not. If it's not empty, your $query insert all three fields. If it is, your $query only inserts $name and $description.
This can be seen in the following (heavily cut-down) code:
/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}
/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);

You have an error in your SQL syntax error message when inserting record

I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";

Form submit PHP code broken only in Wordpress

I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.

SQLi injection prevention and error reporting issues

I know separately these questions are quite common although I have searched around for usable answers and am not having much luck finding a lot of information for MySQLi or the new PHP version. Hopefully one of you experts might be able to help me out.
I have a 'simple' html form running a PHP script to the database, which seems to work perfectly, also includes a file upload, which also works. I have some knowledge over security and protection and I am pretty sure my script isn't at all secure. I am also have problems displaying anything if the script doesn't run properly.
I attempted to add a code such as:
} else {
header('Location: addpcn.php?pcnerror=4');
}
Although there are so many '}' at the end of my code, I am not sure where to add it. Also, there are a lot of issues I may be forgetting to alert the user if the code is unsuccessful and the error would never be displayed?
Here is my code so far:
if(isset($_POST['pcn'])){
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
if(empty($pcn_number) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_reg) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($street_name) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($offence) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_make) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_colour) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($date_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($time_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_from) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_to) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($issued_by) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
mysqli_query($conn, "INSERT INTO parkingtickets (id, pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, special_fine_discount, special_fine, paid, paid_date, evidence) VALUES ('','$pcn_number', '$date_issued', '$vehicle_reg', '$vehicle_make', '$vehicle_model', '$vehicle_colour', '$street_name', '$witnessed_from', '$witnessed_to', '$time_issued', '$offence', '$issued_by', '', '', '0', '', '$name')");
header('Location: addpcn.php?pcnerror=3');
}
}
}
}
}
}
}
}
}
}
}
}
I know that you guys will see it as the wrong way to go about it, but I'm still a novice, and hopefully you'll be able to point me in the right direction with a few better examples as error reporting for this code as well as MySQLi injection prevention could be improved drastically.
Thanks!
I made some changes at your code. For consistency i used underscore for all variables and not the camelCase convention. Same for table name in database (parking_tickets).
It is a good practice to validate your inputs so if one of them isn't of correct type you will be able to show info messages for it.
Also, i used associative arrays instead of multiple if statements.
Thanks to # Scott Arciszewski i added the prepared statements with the difference i omit the paid column so make sure it has 0 as default value in your database.
if (isset($_POST['pcn'])) {
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
//User input validation chekcs
$is_valid = true;
//e.g
if (!(is_numeric((int)$pcn_number) && ctype_digit((string)$pcn_number))) {
$is_valid = false;
echo 'The pcn_number is not valid. It must be an integer.';
}
if (!(is_numeric((int)$vehicle_reg) && ctype_digit((string)$vehicle_reg))) {
$is_valid = false;
echo 'The vehicle_reg is not valid. It must be an integer.';
}
if (!$is_valid) {
//Do something here and dont continue if one of the inputs is not valid
}
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$upload_ok = true;
$image_file_type = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if ($check !== false) {
$upload_ok = true;
} else {
$upload_ok = false;
}
// Check if file already exists
if (file_exists($target_file)) {
$upload_ok = false;
}
// Allow certain file formats
$valid_formats = array('jpg', 'png', 'jpeg', 'gif');
if (!in_array($image_file_type, $valid_formats)) {
$upload_ok = false;
}
// Check if $uploadOk is set to false by an error
if ($upload_ok === false) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
$checks = array(
array (
'var'=>$pcn_number,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
array (
'var'=>$vehicle_reg,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
/*
* More elements here
*/
);
foreach($checks as $key => $value) {
if (empty($value['var']) === $value['condition'] ) {
header('Location: '.$value['location']);
exit;
}
}
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$stmt = mysqli_prepare($connection, "INSERT INTO parking_tickets (pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?");
if (mysqli_stmt_bind_param($stmt, 'sssssssssssss', $pcn_number, $date_issued, $vehicle_reg, $vehicle_make, $vehicle_model, $vehicle_colour, $street_name, $witnessed_from, $witnessed_to, $time_issued, $offence, $issued_by, $name)) {
mysqli_stmt_execute($stmt);
header('Location: addpcn.php?pcnerror=3');
exit;
}
}

Categories