I am trying to post data in updated section but I can't. I am using ajax method for posting. The problems in ifelse loop because if i remove all three if else loop then the data will be posted.
why i use these ifelse logic because if user didn't select date value from input than value should be NULL
<?PHP
if(isset($_POST['action']) && $_POST['action']=="add")
{
add data
}
if(isset($_POST['action'])&& $_POST['action']=="update") //data update
{
update data
}
if(isset($_POST['action']) && $_POST['action']=="delete") //Action for delere
{
delete data
}
elseif(isset($_POST['action'])&& $_POST['action']=="updated")
{
$id=$_POST['edit_id'];
$istatus=$_POST['edit_istatus'];
$idpicker= $_POST["sdatepicker"][0];
$cstatus=$_POST['edit_cstatus'];
$cdpicker= $_POST["sdatepicker"][1];
$rstatus=$_POST['edit_rstatus'];
$rdpicker= $_POST["sdatepicker"][2];
if($i_date=strtotime($idpicker) == false)
{
$iinsertDate=NULL;
}
else
{
$iinsertDate = date("Y-m-d",strtotime($idpicker));
}
if($c_date=strtotime($cdpicker) == false)
{
$cinsertDate=NULL;
}
else
{
$cinsertDate = date("Y-m-d",strtotime($cdpicker));
}
if($r_date=strtotime($rdpicker) == false)
{
$rinsertDate=NULL;
}
else
{
$rinsertDate = date("Y-m-d",strtotime($rdpicker));
}
$test = mysqli_query($conn,"UPDATE status SET istatus='$istatus',idate='$iinsertDate',cdate='$cinsertDate',rdate='$rinsertDate',rstatus='$rstatus',cstatus='$cstatus' WHERE sid='$id'") or die ("Query Wrong");
echo '{"status":"3"}';
exit;
}
?>
Try using this:
if(isset($_POST['action']) && $_POST['action']=="add")
{
// add data
}
if(isset($_POST['action']) && $_POST['action']=="update")
{
//update data
}
if(isset($_POST['action']) && $_POST['action']=="delete")
{
//delete data
}
if(isset($_POST['action']) && $_POST['action']=="updated")
{
$id=$_POST['edit_id'];
$istatus=$_POST['edit_istatus'];
$idpicker= $_POST["sdatepicker"][0];
$cstatus=$_POST['edit_cstatus'];
$cdpicker= $_POST["sdatepicker"][1];
$rstatus=$_POST['edit_rstatus'];
$rdpicker= $_POST["sdatepicker"][2];
$iinsertDate = NULL;
$cinsertDate = NULL;
$rinsertDate = NULL;
if($i_date=strtotime($idpicker) != false)
{
$iinsertDate = date("Y-m-d",strtotime($idpicker));
}
if($c_date=strtotime($cdpicker) != false)
{
$cinsertDate = date("Y-m-d",strtotime($cdpicker));
}
if($r_date=strtotime($rdpicker) != false)
{
$rinsertDate = date("Y-m-d",strtotime($rdpicker));
}
if($iinsertDate != NULL && $cinsertDate != NULL && $rinsertDate != NULL)
{
$test = mysqli_query($conn,"UPDATE status SET istatus = '$istatus', idate = '$iinsertDate', cdate = '$cinsertDate', rdate = '$rinsertDate', rstatus = '$rstatus', cstatus = '$cstatus' WHERE sid = '$id'") or die ("Query Wrong");
echo json_encode(array("status"=>"3"));
}
else
{
//what ever else you want to do
}
}
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;
}
}
I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.
sorry if my question not scene, but when I submit my form no action happen and even no error
appear and I don't know why so please can you help me !!
here my php code
<?php
if (isset ($_POST["submitted"]))
{
if (isset($_POST["proName"]))
{
$namepro=$_POST["proName"];
}
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") ||
($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 200000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"uploads/$filename");
}
}
else
{
echo "invalid file.";
}
if (isset($_POST["selectcat"]))
{
$selectpro=$_POST["selectcat"];
}
if (isset($_POST["shortDescr"]))
{
$desc=$_POST["shortDescr"];
}
else
{$desc=NULL;}
if (isset($_POST["cost"]))
{
$cost=$_POST["cost"];
}
else
{$cost=NULL;}
if (isset($_POST["product"]))
{
$product=$_POST["product"];
}
else
{$product=NULL;}
if (isset($_POST["marketing"]))
{
$mark=$_POST["marketing"];
}
else
{$mark=NULL;}
if (isset($_POST["power"]))
{
$p=$_POST["power"];
}
else
{$p=NULL;}
if (isset($_POST["risk"]))
{
$risk=$_POST["risk"];
}
else
{$risk=NULL;}
if (isset($_POST["compititiors"]))
{
$comp=$_POST["compititiors"];
}
else
{$comp=NULL;}
$teamWork='';
if (isset($_POST["team1"]))
{
$team=$_POST["team1"];
}
if (isset($_POST["s"]))
{
$s=$_POST["s"];
$teamWork=$team."\t\t".$s;
}
if (isset($_POST["team2"]))
{
$team2=$_POST["team2"];
$teamWork=$team."\t\t".$s."<br>".$team2;
}
else
{$team2=NULL;}
if (isset($_POST["s2"]))
{
$s2=$_POST["s2"];
$teamWork=$team."\t\t".$s."<br>".$team2."\t\t".$s2;
}
else
{$s2=NULL;}
if (isset($_POST["team3"]))
{
$team3=$_POST["team3"];
$teamWork=$team."\t\t".$s."<br>".$team2."\t\t".$s2."<br>".$team3."\t\t";
}
else
{$team3=NULL;}
if (isset($_POST["s3"]))
{
$s3=$_POST["s3"];
$teamWork=$team."\t\t".$s."<br>".$team2."\t\t".$s2."<br>".$team3."\t\t".$s3;
}
else
{$s3=NULL;}
$dbc = mysqli_connect("localhost", "root", "", "gettogether");
$q = "INSERT INTO project (projectname,projecttype,personid,imgProject,status,createDate) VALUES
('$namepro','$selectpro',1,'uploads/$filename','unsubmitted',now())";
$r = #mysqli_query ($dbc, $q);
if ($r ) {
$sql="select projectid from project where personid=1 order by createDate desc";
$qur=mysql_query($sql) or die(mysql_error());
if($qur){
$row=mysql_fetch_array($qur);
$proID=$row['projectid'];
$result2 = "INSERT INTO plan (projectid,description,products,marketingplan,financialplan,strenght,risk,team,competitor) VALUES
($proID,'$desc',$product','$mark','$cost','$p','$risk','teamWork','$comp')";
$result=#mysqli_query ($dbc,$result2) or die(mysql_error());
if ($result)
{
header( "Location:project.php" );
}
else
{
echo "error";
}
}
}
else
{ echo" <script>
alert('try again');
</script>
";
}
}
?>
Note :
in my Database I have 2 table one called plan and another called project
and projectid is a foreign key in plan table
before if statement where you are check is submitted is setted put this code to see what is received
echo '<pre>';
print_r($_POST);
echo '</pre>';
Am trying to validate a form and the values of the form can only be inserted into the database if the security answer is correct.Yet the values gets inserted when a wrong answer is given.
if(empty($answer) && (!$answer == $sec_ans)) {
echo "<div class='db_rp'>Error: You did not answer your security question</div>";
} else {
$insert = "INSERT INTO laits SET
p_no = '{$new_pp}',
r_number= '{$r_number}',
memo = '{$memo}',
user= '{$userid}',
acc = '{$acc}'";
if(!mysqli_query($conn, $insert)) {
die('<div class="reply"> There was an error submtting your request ' . mysqli_error($conn)) . '</div>';
}
else {
header("location: tran_su.php");
}
}
Your code is requiring both conditions and should be only one as a minimum.
if(empty($answer) || ($answer != $sec_ans)) {
....
if (empty($answer) || ($answer != $sec_ans)) {