Image not uploading - php

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/

Related

Insert Images PHP Mysql

I'm trying to insert four images to the database but first image only getting inserted. The first image I could fetch but other images are not returned. But in the table image name are showing.
<?php
header("Location:../index.php");
// Create database connection
$db = mysqli_connect("localhost", "root", "", "alu");
// Initialize message variable
$msg = "";
//If upload button is clicked ...
if (isset($_POST['submit'])) {
//Get image name
$txtproducttitle = $_POST['txtproducttitle'];
$txtProductDescription = $_POST['txtProductDescription'];
$txtProdutPrice = $_POST['txtProdutPrice'];
$AdCondition = $_POST['AdCondition'];
$PrImg1 = $_FILES['PrImg1']['name'];
$PrImg2 = $_FILES['PrImg2']['name'];
$PrImg3 = $_FILES['PrImg3']['name'];
$PrImg4 = $_FILES['PrImg4']['name'];
$AdCategory = $_POST['AdCategory'];
$AdLocation = $_POST['AdLocation'];
$txtname = $_POST['txtname'];
$txtuseremail = $_POST['txtuseremail'];
$txtContact = $_POST['txtContact'];
$AdPayment = $_POST['AdPayment'];
$target = "../upload/".basename($PrImg1);
$sql = "INSERT INTO advertisement (AdTitle, AdDes, AdPrice,
AdCondition, AdImg1, AdImg2, AdImg3, AdImg4, AdCategory, AdLocation,
AdSellName, AdSellMail, AdSellContact, AdPayment)
VALUES ('$txtproducttitle','$txtProductDescription','$txtProdutPrice','$AdCondition','$PrImg1','$PrImg2','$PrImg3','$PrImg4','$AdCategory','$AdLocation','$txtname','$txtuseremail','$txtContact','$AdPayment')";
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['PrImg1']['tmp_name'], $target)) {
$msg = "Ad Successfully Posted";
}else
{
$msg = "Failed To Post Ad";
}
}
$result = mysqli_query($db, "SELECT * FROM advertisement");
You need to use move_uploaded_file function for other images.
Use:
if (move_uploaded_file($_FILES['PrImg2']['tmp_name'], $target2)) {
$msg = "Ad2 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg3']['tmp_name'], $target2)) {
$msg = "Ad3 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg4']['tmp_name'], $target2)) {
$msg = "Ad4 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad4";
}

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.

Image moving to folder but not saving the row in database

Everything was working fine until i decided to add a new product and nothing works , the picture is uploading to the folder but the problem is coming from the move_uploaded_file function , the thing is the function is working and moving pictures but the code is not moving to the next instruction does anyone have an idea about this error ?
<?php
if ($_POST) {
$productName = $_POST['productName'];
$quantity = $_POST['quantity'];
$rate = $_POST['rate'];
$brandName = $_POST['brandName'];
$categoryName = $_POST['categoryName'];
$genderName = $_POST['genderName'];
$sizeName = $_POST['sizeName'];
$productStatus = $_POST['productStatus'];
$type = explode('.', $_FILES['productImage']['name']);
$type = $type[count($type) - 1];
$url = '../assests/images/stock/' . uniqid(rand()) . '.' . $type;
if (in_array($type, ['gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'])) {
if (is_uploaded_file($_FILES['productImage']['tmp_name'])) {
if (move_uploaded_file($_FILES['productImage']['tmp_name'], $url)) {
$sql = "INSERT INTO product (product_name, product_image, brand_id, categories_id, quantity, price, active, status,gender_id,size_id,description,dateadded,discount)
VALUES ('$productName', '$url', '$brandName', '$categoryName', '$quantity', '$rate', '$productStatus', 1,'$genderName','$sizeName')";
if ($connect->query($sql) === true) {
echo "<SCRIPT type='text/javascript'> //not showing me this
alert('Product added !');
window.location.replace(\"http://localhost/stock/product.php\");
</SCRIPT>";
} else {
$valid['success'] = false;
$valid['messages'] = "Error while adding the members";
}
} else {
echo "lool";
}
}
}
$connect->close();
}
?>
I don't see the variable $connect declared anywhere in your code. It is possible that you have error reporting disabled and the script dies on
if ($connect->query($sql) === true) {
because $connect is undefined?

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; when try to submit form

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2
I got the above error when submitting the form.
<?php
session_start();
$branch=$_SESSION['branch'];
include('../dist/includes/dbcon.php');
$name = $_POST['prod_name'];
$price = $_POST['prod_price'];
$desc = $_POST['prod_desc'];
$supplier = $_POST['supplier'];
$reorder = $_POST['reorder'];
$category = $_POST['category'];
//$quantity = $_POST['prod_qty'];
$serialn = $_POST['serialn'];
$query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
$count=mysqli_num_rows($query2);
if ($count>0)
{
echo "<script type='text/javascript'>alert('Product already exist!');</script>";
echo "<script>document.location='product.php'</script>";
}
else
{
$pic = $_FILES["image"]["name"];
if ($pic=="")
{
$pic="default.gif";
}
else
{
$pic = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$error = $_FILES["image"]["error"];
if ($error > 0)
{
die("Error uploading file! Code $error.");
}
else{
if($size > 100000000000) //conditions for the file
{
die("Format is not allowed or file size is too big!");
}
else
{
move_uploaded_file($temp, "../dist/uploads/".$pic);
}
}
}
mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));
echo "<script type='text/javascript'>alert('Successfully added new product!');</script>";
echo "<script>document.location='product.php'</script>";
}
?>
Looks like you're missing a single quote before $reorder' ?
You have missed ' before $reorder try this code
mysqli_query($con,"INSERT INTO product(prod_name, prod_price, prod_desc ,prod_pic, cat_id, reorder, supplier_id, branch_id, serialn) VALUES ('$name', '$price', '$desc', '$pic', '$category', '$reorder', '$supplier', '$branch', '$serialn')")or die(mysqli_error($con))or die(mysqli_error($con));
Error in your SQL INSERT Query.
mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
VALUES('$name','$price','$desc','$pic','$category','$reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con))
try now..

Categories