I want to upload an image to my server and save the image path to my database,
How can I rename the file to its auto-incrementing id? And save the path to DB
I mean if I have a file image.jpg. when I upload the image I want to rename it automatically to corresponding id.jpg (eg 1.jpg, 2.jpg 3.jpg etc ) and save that path to the database.
Here's the code I've now. But it's not working.
<?php
include 'db.php';
$title = $_POST['title'];
$description = $_POST['description'];
$lang = $_POST['lang'];
$fileName = $_FILES['file']['name'];
$target = "img/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["file"]["tmp_name"];
$result =
move_uploaded_file($tempFileName,$fileTarget);
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName',$fileTarget',CURDATE()),'$lang'");
if($add){
echo "File uploaded successfully";
}
else{
echo "Sorry upload failed.";
}
?>
Here's my form
<html>
<body>
<form name="upload" method="POST" action="upload.php" onsubmit="return validateform()" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="text" name="description"><br>
<select name="lang">
<option value="Malayalam">Malayalam</option>
<option value="Tamil">Tamil</option>
<option value="Telugu">Telugu</option></select><br>
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
I think you have an issue with your insert query check here what the mistake I found...
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName','$fileTarget',CURDATE(),'$lang')");
There ')' is wrongly added near to CURDATE() and also a ' missed for $fileTarget and not well-ended insert query you create use above code for the same,
Related
I want to insert some data to database by query in PHP. I have something like this.
$zp='INSERT INTO `user`(`name`, `password`, `avatar`) VALUES ("'.$_POST['login'].'","'.$_POST['password'].'")';
And i want to put in the third value
<img src="$file_name.$file_type"/>
But I have no idea how to write this in PHP query
You need to create an upload functionality, and to save only the path where you're images are stored.
Create a table in your database, with few column names: filepath, mime, size.
A little example: index.php:
if(isset($_FILES['file']['name'])){
$name = $_FILES['file']['name'];
$mime = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
$path = 'uploads/' . $name; //maybe you should create the uploads/ folder before running the script
if(move_uploaded_file($tmp, $path)){
$db = new PDO('mysql:host=localhost;dbname=your_db_name','your_db_user','your_db_pass');
$stmt = $db->prepare('INSERT INTO your_table_name_here SET filepath=?,mime=?,size=?');
$stmt->execute([$path,$mime,$size]);
echo 'File uploaded successfully!';
}
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
Then you can grab all the saved paths, and add them as src attrbuite for your images.
//index.php
$stmt = $db->prepare('SELECT filepath FROM your_table_name_here');
$stmt->execute();
while($row = $stmt->fetch()){?>
<img src="<?php echo $row['filepath']; ?>" alt="image">
<?php }
But notice this is just a super simple script, for your learning purposes, and this code must not be used in production mode, as is not safe.
I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:
<html>
<body>
<form action="image.php" method="post" enctype="multipart/form-data">
<input type="text" name="image_description" placeholder="Enter name" required>
<input type="file" name="myfile">
<input type="submit" name="upload" value="upload">
</form>
</body>
</html>
<?php
include("db.php");
if(isset($_POST['upload'])) {
$image_description = $_POST['image_description'];
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
$upload=move_uploaded_file($temp, "uploaded/" . $name);
$query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
if(mysqli_query($conn,$query) && $upload) {
echo "successfully uploaded";
}
else
die(mysqli_error($conn));
}
$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
<img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
echo $row['image_description'] . "<br>";
}?>
Images are displayed as in picture
This is database table
The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.
Use root-relative URLs: src="/uploaded/.."
or use relative URLs but go to the right folder: src="../uploaded/.."
or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.
This code was run on my localhost. The images are uploaded to my mysql server using the localhost wampserver. Everything seems to be good. But when I migrate the code to the hosting site, I can't see the image uploaded in the mysql server. All I can see is my path "images-storage/" as the value of "photo" column, "images-storage" is empty and no image is stored.
This is the code:
My Form:
<form action="add.php" method="POST" enctype="multipart/form-data">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br /><br />
<input type="file" name="image">
<input type="submit" value="Submit">
</form>
My form action:
<?php
include_once('config.php');
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
$name = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$error = $_FILES["image"]["error"];
if($error > 0) {
echo "Error";
} else {
$add_image = move_uploaded_file($temp,"uploaded/".$name);
$path = 'uploaded/'.$name;
$query = $mysqli->query("INSERT INTO info(fn,ln,name,photo) VALUES('$fn','$ln','$name','$path')");
}
header('Location: index.php');
?>
Just add "name" column in the database. Haha
I have created a PHP signup form for visitors to fill and submit that asks for their basic information.
I am trying to accomplish the following two tasks;
Add Image/File Upload Field
Redirect them to a confirmation page
I have been unable to make it work. Below is what I have.
My Code
HTML Form
<form name="form1" method="post" action="signup.php">
Username: <input type="text" name="user">
<br>Email: <input type="text" name="mail">
<br>Experience: <select name="exp"> <option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option> <option value="advanced">Advanced</option>
</select><br> <input type="submit" name="Submit" value="Sign Up">
</form>
Signup.php
<?php
$username = $_POST['user'];
$email = $_POST['mail'];
$experience = $_POST['exp'];
//the data
$data = "$username | $email | $experience\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
?>
It seems like you lack an input field in your HTML to begin with.
here's an example of a form for uploading files.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Once you've done that you're not quite there yet because your file is stored in a temporary folder, you will need to move the file to your uploads folder like so:
$target_file = "uploads/" . basename ($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
I hope this helps!
Ta add an upload you need to add enctype="multipart/form-data" to your form tag,then add the upload field. For the Email field change the type to HTML5 type="email", this will do a little validaation check that it is in the correct format. At the bottom of the php file add a location header if all went well. You could put it all in one file with an if statement at the top.You should also sanitize your inputs
this is a upload file script which will loop through all the data of a file and insert
if(isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name']. "uploaded successfully." . "</h1>";
}
$csv_file=$_FILES['filename']['tmp_name'];
$type=$_FILES['filename']['type'];
$handle = fopen($csv_file, "r");
$i=0;
while (($data = fgetcsv($handle)) !== FALSE) {
if($i>0) {
$import="insert into `table_name`(col1,col2,col3,col4,col5,col6,col7)values('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."','".addslashes($data[4])."','$data[5]','$data[6]')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
echo "Success";
echo "<br>";
echo $_FILES['filename']['type'];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="" id="">
Choose File:<br>
<input name="filename" type="file" />
<input type="submit" name="submit" value="submit" />
</form>
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.
Here is my code:
<?php
require "connect.php";
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
</div>
Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.
The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:
$uploaddir="C:/wamp/www/admirovsajt/uploaded"
But same problem.
Verify that image was uploaded before looking for correct path in the database.
instead of:
$uploaddir = 'uploaded';
try
$uploaddir = 'uploaded/';
Try:
<?php
require "connect.php";
if(isset($_GET['id'])) {
echo $id = $_GET['id'];
}
$uploaddir = 'uploaded/';
if(isset($_POST['submit'])) {
$pid = $_POST['pid'];
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="pid" value="<?php echo $id;?>">
<input type="file" name="image"/>
<input name="submit" type="submit" value="upload"/>
</form>
</div>