Condition to Skip Input field if Empty - php

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

Related

inserting csv file data into mysql databse using php

This is my html page for adding data
php script for inserting data into database placements and csv file into "eligilist" database. NOTE: the rownd1,rownd2.... are javascript event based on number of rounds are selected then javascript code shows number of selection boxes which is rownd1, rownd2,rownd3 so these are the values based on user selection.
<?php
require_once('dbconfig/config.php');
if(isset($_POST['submit']))
{
$name = $_POST['placename'];
$eligibility = $_POST['elig'];
$backlogs=$_POST['blogs'];
$rounds=$_POST['rownds'];
if( isset($_POST["rownd1"]) && isset($_POST["rownd2"] ) && isset($_POST["rownd3"] ) && isset($_POST["rownd4"] ))
{
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=$_POST['rownd3'];
$round4=$_POST['rownd4'];
}
elseif (isset($_POST["rownd1"]) && isset($_POST["rownd2"] ) && isset($_POST["rownd3"] )) {
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=$_POST['rownd3'];
$round4=NULL;
}
elseif (isset($_POST["rownd1"]) && isset($_POST["rownd2"] )) {
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=NULL;
$round4=NULL;
}
elseif (isset($_POST["rownd1"]))
{
$round1=$_POST['rownd1'];
$round2=NULL;
$round3=NULL;
$round4=NULL;
}
$venu=$_POST['location'];
$date=$_POST['InterviewTime'];
$fileName = $_FILES['myFile']['name'];
$fileTmpName = $_FILES['myFile']['tmp_name'];
$fileExtension = pathinfo($fileName,PATHINFO_EXTENSION);
$allowedType = array('csv');
if(!in_array($fileExtension, $allowedType))
{
echo '<script type="text/javascript"> alert("invalid file extension")</script>';
} else{
$handle = fopen($fileTmpName,'r');
while (($myData = fgetcsv($handle,1000,',')) !== FALSE){
$fname = $myData[0];
$regno = $myData[1];
$branch = $myData[2];
$percentage = $myData[3];
$back_logs = $myData[4];
$mobile = $myData[5];
$email = $myData[6];
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email) VALUES (NULL,".$fname.",".$regno.",".$branch.",".$percentage.",".$back_logs.",".$mobile.",".$email.")";
$query_run = mysqli_query($con,$query);
}
$query1 = "INSERT INTO `placements` (`id`,`name`,`eligibility`,`backlogs`,`rounds`,`round1`,`round2`,`round3`,`round4`,`venu`,`date`) VALUES (NULL,'$name','$eligibility','$backlogs','$rounds','$round1','$round2','$round3','$round4','$venu','$date')";
$query_run1 = mysqli_query($con,$query1);
if($query_run && $query_run1)
{
echo '<script type="text/javascript"> alert("Successfully added")</script>';
}
else
{
echo '<script type="text/javascript"> alert("Error!")</script>';
}
}
}
}
?>
my problem is when i was submit all data along with csv file it shows error...but the except csv file remaining data are inserted into placements database the only problem with csv file not storing in eligilist table in databse...please help me and resolve my code if any errors...thank you.
You need quotes round the field values in your insert (the same way you do it for the placements table)...
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email)
VALUES (NULL,'$fname','$regno','$branch','$percentage','$back_logs','$mobile','$email')";
BUT you should be using prepared statements and bind variables as this helps prevent several problems...
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email)
VALUES (NULL,?,?,?,?,?,?,?)";
$prep = mysqli_prepare ( $con,$query );
$handle = fopen($fileTmpName,'r');
while (($myData = fgetcsv($handle,1000,',')) !== FALSE){
$fname = $myData[0];
$regno = $myData[1];
$branch = $myData[2];
$percentage = $myData[3];
$back_logs = $myData[4];
$mobile = $myData[5];
$email = $myData[6];
mysqli_stmt_bind_param($prep, "sssssss", $fname,
$regno, $branch, $percentage, $back_logs,
$mobile, $email );
mysqli_stmt_execute($prep);
}

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering.
here is my code:
include("includes/db.php");
if (isset($_POST['submit']) && $hidden == "" ) {
$product = mysqli_real_escape_string($bd, $_POST['product']);
$name = mysqli_real_escape_string($bd, $_POST['name']);
$address = mysqli_real_escape_string($bd, $_POST['address']);
$coupon = mysqli_real_escape_string($bd, $_POST['coupon']);
date_default_timezone_set("Asia/Kolkata");
$dates = date('Y-m-d H:i:s');
if (isset($_FILES["invoice_copy"]["name"])) {
$imgpancard = $_FILES["invoice_copy"]["name"];
$tmp_name = $_FILES['invoice_copy']['tmp_name'];
$error = $_FILES['invoice_copy']['error'];
if (!empty($imgpancard)) {
$location = 'doc/';
if (move_uploaded_file($tmp_name, $location.$imgpancard)){
//echo 'Uploaded';
}
}
}
$query = mysqli_query($bd, "SELECT * FROM customer WHERE coupon='".$coupon."'");
if(mysqli_num_rows($query) > 0) {
echo'<script> alert("COUPON ALEARDY EXISTS!");
window.location="register.php";
</script> ';
}
else {
$sql = "INSERT INTO customer (product, customer_name, address, coupon, RegistrationDate, invoice_copy) VALUES ('$product', '$name', '$address', '$coupon', '$dates', '$imgpancard')";
if(mysqli_query($bd, $sql)){
echo'<script> alert("DATA SUBMITTED SUCCESFULLY!");
window.location="index.html"; </script> ';
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($bd);
}
}
}
how to of 10 times one times blank data is inserted.how to avoid it can please tell me , whether code is wrong or not. In every input feild i have used required attribute

query wongt output to table. correct syntax

What am i doing wrong here?
(Know its mysql)
this else is not working it look like. user can insert same modul id many times.
$besvarelse = $_GET['besvarelse'];
$modulid = $_GET['modulid'];
$username = $_GET['username'];
$tilkobling = kobleTil();
if (!empty($besvarelse) ) {
$insert = mysql_query("INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')");
if($insert) {
echo "<h1>Levering OK</h1><br>";
}
}
else {
die("<h1>Du har lever før</h1>");
}
?>
Try with this and post the errors that PHP shows, please:
//Assuming that connection to mysql server its done somewhere with mysql_connect()
error_reporting(E_ALL); ini_set('display_errors', 1);
explode($_GET);
echo "<pre>";
print_r($_GET); //Just to see what's on the variables...
echo "</pre>;
// $tilkobling = kobleTil(); Need to explain this line
if (!empty($besvarelse) ) {
$sql = "INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')";
if($insert = mysql_query($sql))
{
echo "<h1>Levering OK</h1><br>";
}
else {
die("<h1>Du har lever før</h1>");
}
} // you were missmatching the IF closing bracket
?>
try to check for exist rows like
$besvarelse = $_GET['besvarelse'];
$modulid = $_GET['modulid'];
$username = $_GET['username'];
$tilkobling = kobleTil();
if (!empty($besvarelse) ) {
// check exist moduleid
$check = mysql_query("select * from oppgave where modulid = '$modulid'");
$conut_rows= mysql_num_rows($check);
if($conut_rows > 0) {
echo "module id already exist";
}
else {
$insert = mysql_query("INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')");
if($insert) {
echo "<h1>Levering OK</h1><br>";
}
else {
die("<h1>Du har lever før</h1>");
}
}
}

Echo error message if one input value is greater than other in php

I have a form that saves 5 input values to an inventory in data base. The problem is, i need it to return an error message if "Value" is larger than "Buy_Value". Right now it prints the error message, but still submits the data to data base which is no use for me. Am I just using the function in the wrong place in the code?
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['ID'])&&isset($_POST['Name'])&&isset($_POST['Inventory_number'])
&&isset($_POST['Value'])&&isset($_POST['Buy_Value'])){
$ID=$_POST['ID'];
$Name=$_POST['Name'];
$Inventory_number=$_POST['Inventory_number'];
$Value=$_POST['Value'];
$Buy_Value=$_POST['Buy_Value'];
//echo "<p>".$ID." ".$Name." ".$Inventory_number."</p>";
include('config.php');
if ($Value > $Buy_Value) {
echo("The 'buy value' must be greater than 'value'");
}
$sql="INSERT INTO $mysql_database.`inventory`
(`id`, `Name`, `Inv_Nr`, `value`, `buy_value`)
VALUES ('$ID', '$Name', '$Inventory_number', '$Value', '$Buy_Value')";
$result=mysql_query($sql);
tab($sql);
mysql_close($bd);
}
}
function tab($sql){
if (!mysql_errno())
{
echo "<br />Data submitted";
}
else
{
echo "<br />Error: " . mysql_error();
}
}
?>
Use exit instead of echo for the following line
exit("The 'buy value' must be greater than 'value'");
put your database query execution in else part then it will not executed if below
if ($Value > $Buy_Value) {
condition is meet.
try this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['ID']) && isset($_POST['Name']) && isset($_POST['Inventory_number'])
&& isset($_POST['Value']) && isset($_POST['Buy_Value'])
) {
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$Inventory_number = $_POST['Inventory_number'];
$Value = $_POST['Value'];
$Buy_Value = $_POST['Buy_Value'];
//echo "<p>".$ID." ".$Name." ".$Inventory_number."</p>";
include('config.php');
if ($Value > $Buy_Value) {
echo("The 'buy value' must be greater than 'value'");
} else {
$sql = "INSERT INTO $mysql_database.`inventory`
(`id`, `Name`, `Inv_Nr`, `value`, `buy_value`)
VALUES ('$ID', '$Name', '$Inventory_number', '$Value', '$Buy_Value')";
$result = mysql_query($sql);
tab($sql);
mysql_close($bd);
}
}
}
function tab($sql)
{
if (!mysql_errno()) {
echo "<br />Data submitted";
} else {
echo "<br />Error: " . mysql_error();
}
}

Image not uploading

i am having trouble trying to upload an image to a website, and update the database with the address of the image. All of the other fields are being correctly added to the database, except for the image address, and the image is not being saved in the images folder. I have absolutely no idea whats wrong, and when i try to upload an image it echoes there was a problem uploading your file. Thanks a lot for the help.
<?php
if($_REQUEST['submit'])
{
function isChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$target = "~start/B7/images/";
$target = $target . basename( $_FILES['photo']['name']);
$age = $_POST["age"];
$brand = $_POST["brand"];
$model = $_POST["model"];
$price = $_POST["price"];
$vechicleType = $_POST["vechicleType"];
$fuelType = $_POST["fuelType"];
$transmition = $_POST["transmition"];
$doorsNumbers = $_POST["doorsNumbers"];
$mileage = $_POST["mileage"];
$pic = ($_FILES['photo']['name']);
//Connect to the server
$con = mysql_connect("*********", "*********", "*********")
or die('Could not connect:' . mysql_error());
// Select database
mysql_select_db("*********", $con)
or die('Could not select database');
// Select all the names from the database
$checkName = mysql_query("SELECT * FROM users");
while ($number = mysql_fetch_array($checkName))
{
$index = 0;
if (($number['user_name'] == $name) && ($number['password'] == $password)
|| isset($_SESSION['test']))
{
$index = 1;
$_SESSION['test']=$name;
$_SESSION['id']=$number['user_id'];
}
}
// Select all the names from the database
$checkName = mysql_query("SELECT * FROM used_cars");
if (!empty($model))
{
if(isChecked('extras', 'leather'))
$leather = "yes";
if(isChecked('extras', 'airCon'))
$airCon = "yes";
if(isChecked('extras', 'satNav'))
$satNav = "yes";
if(isChecked('extras', 'parkingSensors'))
$parking = "yes";
$insert1="INSERT INTO used_cars (manufacturer, model, price, image, vehicleType,
age, transmission, fuelType, doorsNumber, user_id, colour, mileage,
leatherSeat, navigatorSystem, parkingSensor, airConditioner) VALUES ('$brand', '$model', '$price', '$pic', '$vechicleType',
'$age', '$transmition', '$fuelType', '$doorsNumbers', '$user_id',
'$colour', '$mileage', '$leather', '$satNav', '$parking', '$airCon')";
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file was uploaded";
}
else
{
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
else
{
echo 'Please fill in all fields';
}
mysql_close($con);
}
?>
As explained further in the comments, your path should probably be images/

Categories