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.
Related
I am trying to insert a title, description and an image into an sql database, below is the form.
However, the code breaks after the form is submitted. I get redirected to the next page but none of the code in the next file gets processed.
It worked fine before I added the function to add an image and there was just text.
here is the code for the form that does not get processed correctly:
<?php
if (isset($_SESSION['username'])) {
echo "<form action='/origo/addnewtopic.php?cid=".$_GET['cid']."&scid=".$_GET['scid']."'
method='POST' enctype='multipart/form-data'>
<p>Titel: </p>
<input type='text' id='topic' name='topic' size='100' />
<p>Innehåll: </p>
<textarea id='content' name='content'></textarea><br />
<input type='file' name='image'>
<input type='submit' value='Lägg till' name='submit'/></form>"; ?>
And if anyone wonders, this is the file that it sends the info to that is trying to insert text and image to the database, but none of this gets processed.
<?php
session_start();
include ('dbconn.php');
$topic = addslashes($_POST['topic']);
$content = nl2br(addslashes($_POST['content']));
$image = ($_FILES['image']);
$cid = $_GET['cid'];
$scid = $_GET['scid'];
$insert = mysqli_query($con, "INSERT INTO topics (`category_id`, `subcategory_id`, `author`, `title`, `content`, `date_posted`)
VALUES ('".$cid."', '".$scid."', '".$_SESSION['username']."', '".$topic."', '".$content."', NOW());");
$tid = mysql_insert_id();
die($tid);
if($image) {
$insert2 = mysqli_query($con, "INSERT INTO images (`category_id`, `subcategory_id`, `topic_id`, `image`)
VALUES ('".$cid."', '".$scid."', '".$tid."', '".$image."');
}
else {
die("no image");
}
if ($insert) {
header("Location: /origo/topics.php?cid=".$cid."&scid=".$scid."");
} else {
die("error");
}
?>
try using blob datatype in the DB.
also here
$content = nl2br(addslashes($_POST['content']));
You must use $_FILES rather than $_POST. As the files like images are being stored in an array $_FILES that is later being extracted from. Also you must use file_get_contents for :
$content = nl2br(addslashes(file_get_contents($_POST['content'])));
Hope this helps a little
I have tried to insert image from database using php PDO. i have not save image directly i have store image path in my database. i am store in image path in my database.
<?php
//This is a database connection
$conn = new PDO("mysql:host=localhost; dbname=newdb;", 'root', '');
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- This is a post type form it is a upload images -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="img" required /><br><br>
<button type="submit" name="submit-img">Store Image</button>
</form>
</body>
<html/>
<?php
if (isset($_POST['submit-img']))
{
$type = ['image/jpg', 'image/png', 'image/jpeg']; //Image type name
$img = $_FILES['img']; //Fetch files
if (in_array($img['type'], $type)) //Check file type is image or not
{
$file_tmp_name = $_FILES['img']['tmp_name'];
$file_name = $_FILES['img']['name'];
$folder = "images/".$file_name;
echo $folder;
if (move_uploaded_file($file_tmp_name, $folder)) //Upload image in folder
{
$sql = "INSERT INTO images (img) VALUES (?)";
$insert_img = $conn->prepare($sql);
if ($insert_img->execute([$file_name])) //This is a image path store in database
{
echo "<script>alert('image upload successfully...')</script>";
}
else
{
echo "Image cannot uploaded please try again";
}
}
else
{
echo "file cannot uploaded";
}
}
else
{
echo "<br>Please upload an image";
}
}
?>
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'm actively learning php and am working on a CMS Project. I'm stuck on image upload.
PHP
if ( $_POST['img'])
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
HTML
<img src="images/$image" />
MySQL
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
The name of the file is uploaded to database but the file itself is not being uploaded to the destination folder.
Type your html code in between form and in the form wrtie as following
<form action="" method="post" enctype="multipart/form-data">
<img src="images/$image" name="img" />
...
</form>
Use $_FILES to check file is posted or not instead of $_POST. Also make proper quote for variables. Then for echo php variable use php tags.
Try
PHP:
if ( $_FILES['img'])
$uploads_dir = 'images'; // will be on same location where php file exist.
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, $uploads_dir.'/'.$name);
HTML:
<img src="images/<?php echo $image;?>" />
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
// Upload multiple files to the folder
$upload_dir = '/images';
if ( $_FILES['img']){
foreach ($_FILES["img"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["img"]["tmp_name"][$key];
$name = $_FILES["img"]["name"][$key];
move_uploaded_file($tmp_name, "$upload_dir/$name");
}
}
}
//MySQL
MySQL:
$sql = "INSERT INTO affordplan VALUES('$title','$name','$bodytext','$created')";
return mysql_query($sql);
HTML used in form submission
<input type="file" name="img" multiple>
Showing the images in HTML
$dir = "/images/";
$images = glob($dir."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
You are assigning a directory that is equivalent to the file name. Try this
<?php
if (!file_exist("your main directory/the file to story")) {
mkdir("your main directory/the file to story", 0777, true);
}
// then you start uploading your once the folder is created
?>
The process here is if the folder directory doesn't exist, the mkdir() function will create that folder. Then that's the time you start on moving the file to the created folder.
Put all of your code in if statement:
if ( $_POST['img']) {
$uploads_dir = '/images';
$tmp_name = $_FILES["img"]["tmp_name"];
$name = $_FILES["img"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
<form action="phpfilename.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload Image" name="submit">
$file=$_FILES['file']['name'];
$dest="uploads/$file";
$src=$_FILES['file']['tmp_name'];
move_uploaded_file($src,$dest);
$result=mysql_query("insert into tablename(dbfieldname) values('$dest')");
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>
I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"