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>
Related
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,
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.
I have this code for a form that uploads pictures to my website and saves the information to a mysql database:
<form method='post'>
Album Name: <input type="text" name="title" />
<input type="submit" name="submit" value="create" />
</form>
<h4>Add Photo</h4>
<form enctype="multipart/form-data" method="post">
<?php
require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST['upload'])){
$caption = $_POST['caption'];
$albumID = $_POST['album'];
$file = $_FILES ['file']['name'];
$file_type = $_FILES ['file']['type'];
$file_size = $_FILES ['file']['size'];
$file_tmp = $_FILES ['file']['tmp_name'];
$random_name = rand();
if(empty($file)){
echo "Please enter a file <br>";
} else{
move_uploaded_file($file_tmp, 'uploads/'.$random_name.'.jpg');
$ret = mysqli_prepare($mysqli, "INSERT INTO photos (caption, image_url, date_taken)
VALUES(?, ?, NOW())");
$filename = "uploads/" + $random_name + ".jpeg";
mysqli_stmt_bind_param($ret, "ss", $caption, $filename);
mysqli_stmt_execute($ret);
echo "Photo successfully uploaded!<br>";
}
}
?>
Caption: <br>
<input type="text" name="caption">
<br><br>
Select Album: <br>
<select name="album">
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT * FROM albums");
while ($row = $result->fetch_assoc()) {
$albumID = $row['albumID'];
$title = $row['title'];
echo "<option value='$albumID'>$title</option>";
}
?>
</select>
<br><br>
Select Photo: <br>
<input type="file" name="file">
<br><br>
<input type="submit" name="upload" value="Upload">
</form>
This successfully uploads the picture to my 'uploads' folder as well as my mysql database, however, I would like to put in image URL "uploads/(random name generated).jpg"
I have failed to do this with my current code, the information recorded in the 'image_url' column of my photos table is just the random number generated. without the "uploads/" in the beginning and ".jpg" in the end.
I should mention that the schema for my photos table is:
caption, image_url, date_taken, imageID
Any help will be very much appreciated!!
thank you in advance
You are using + (plus) signs to concatenate with, in this line:
$filename = "uploads/" + $random_name + ".jpeg";
PHP uses dots/periods to concatenate with, rather than plus signs which is JS/C language syntax:
$filename = "uploads/" . $random_name . ".jpeg";
Error checking would have signaled the syntax error.
I have a problem when moving an uploaded file into a local directory.
When running the following code, the output is always "error uploading file". It seems to always not meet the condition for the 'move_uploaded_media' function and therefore $result is not being set?
Are there any glaring mistakes?
<?php
$page_title = 'Admin | Multimedia Portfolio';
include('includes/admin_header.html');
if(isset($_POST['submitted']))
{
$uploadDir = 'files/';
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file"; // Here is were the it always gets caught
exit;
}
require_once('mysql_connect.php');
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO files (name, size, type, path ) VALUES ('$fileName', '$fileSize', '$fileType', '$filePath')";
mysqli_query($dbc, $query) or die('Error, query failed : ' . mysql_error());
mysqli_close($dbc);
echo "<br>Files uploaded<br>";
}
?>
<div id="content-wrap">
<h1>Upload Media</h1>
<div id="content">
<form method="post" action="upload.php" encytype="multipart/form-data">
<fieldset>
<div class="entry">
<label>Which media <span class="highlight">file</span> would you like to upload?</label>
<input type="file" name="userfile" id="userfile" size="30" />
</div>
<fieldset id="button">
<input type="submit" value="Register" />
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</fieldset>
</form>
</div>
</div>
<?php
include('includes/admin_footer.html');
?>
Not sure if there is more, but you have encytype instead of enctype in your <form>.
You might also want to perform an is_uploaded_file() check on the temporary file, just to be sure...