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";
}
Related
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')";
I made simple upload system with using class.upload.php and it works great while adding new into database. But i have problem when i need to edit my entry. While editing entry i don't want to edit image but it sent it blank, also if i select image again it sent it blank too. Here is my code.
Can explain my problem.
<?php require_once("conn.php");
require_once ("class.upload.php");
$catid = $_POST['catid'];
$title = $_POST['title'];
$descc = $_POST['descc'];
$keyw = $_POST['keyw'];
$message = $_POST['message'];
$Image = $_FILES['Image'];
$randnum = rand();
$foo = new upload($Image);
$filee = './Image';
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
$Image7 = $foo->file_dst_name;
if($_GET[pass] == 1)
{
if(!isset($_POST[catid]) || empty($_POST[catid])){
$hata = "Required area.";
}
if(!isset($_POST[title]) || empty($_POST[title])){
$hata = "Required area.";
}
if(!isset($_POST[descc]) || empty($_POST[descc])){
$hata = "Required area.";
}
if(!isset($_POST[keyw]) || empty($_POST[keyw])){
$hata = "Required area.";
}
if(!isset($_POST[message]) || empty($_POST[message])){
$hata = "Required area.";
}
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image='$_POST[Image]'
WHERE id='$_POST[id]'
");
$mesaj = "OK!";
}
}
$sonuc = mysql_query("select * from product WHERE id='$_GET[product]'");
$edit = mysql_fetch_array($sonuc);
$sonuc1 = mysql_query("select * from category");
$edit1 = mysql_fetch_array($sonuc1);
?>
try to change the update query
at Image='$_POST[Image]'
with Image='$Image7'
Fatih you can use a variable (i.e. $saved_image_name) instead of $POST[Image] at sql query. Set this variable to new name if uploaded else old value of db field.
...
...
$foo = new upload($Image);
$filee = './Image';
$saved_image_name = " Image "; // name of db field.
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
// Note the quotes
$saved_image_name = " '$foo->file_dst_name' ";
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
// no use anymore $Image7 = $foo->file_dst_name;
...
...
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image= $saved_image_name // note the quotes
WHERE id='$_POST[id]'
");
...
...
Hello everyone i'm able to display my record by passing an id by query string to another page, but i'm not able to update it, the problem is that when i click on update nothing happen, it return me a blank page, and there is no printed error, can someone help me please?
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
At this stage, the code display every information i need , the stage below is where i'm having a problem, i'm not able to get the id against and make the update when click on update button
elseif (!empty($_POST) and !empty($_GET['id']) ) {
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$id = $_REQUEST['id'];
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
First thing, when you get a blank page, check your error log. Or if you're lazy, add this at the begining of your file to get error messages.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
It's hard to say, but just looking at your code quickly, I see a problem with your mixup of $_GET and $_POST. From what I gather, since your SELECTworks, you send data in $_GET, and your UPDATE block is only executed if you have $_POST data.
Change your html <form method="get"> for <form method="post">
And change your select block to check if( !empty($_POST['id'])) {
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/
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.