So I have "staff" table in database i.e. StaffName, StaffAddress and StaffProfilePicture etc. Updating works fine on name, address but not the picure. The old picture seems to be missing from the database eventhough I don't upload a new one.
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
//echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
//echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
//echo "<img src='" . $imageup . "' />";
} else {
//echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = $mysqli->query("UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'");
$success = mysql_query($query1);//is mysql query working?
if($success){
//$oldprofilepicture = $staff['StaffProfilePicture'];
//if(file_exists($oldprofilepicture)){
//unlink($oldprofilepicture);//delete now
echo "success";
header('location:staff_profile.php');
die;
}else{
echo "failed";
}
}
Below is the HTML form for the picture
<tr>
<td width="170">Old Profile Picture:</td>
<td><img src="<?php echo $profilepicture ?>" width="100" height="80" /><br><br>
<input type="file" name="new_profilepicture" />
</tr>
How can I make the old/existed picture stay?
On your query you have:
StaffProfilePicture='$_var8'
so it still updates the database and since $imageup is empty/undefined so is $_var8 and it will update the database with empty value.
So add an if condition:
$_var8 = $imageup;
if($_var8 != '') {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8' WHERE StaffID='$staffID'");
} else {
$query1 = $mysqli->query("UPDATE staff SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7' WHERE StaffID='$staffID'");
}
or you can do it other ways but that's where your problem is that you're losing your old image. Hope it helps.
Cheers.
Related
I want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>
Here is code of uploading image in my localhost/file/img folder and also inserting image path and name in my table.
<?php
if (isset($_POST['submit']))
{
$file_id = $_POST['file_id'];
if (count($_FILES['upload']['name']) > 0)
{
for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$shortname = $_FILES['upload']['name'][$i];
$filePath = "img/" . $_FILES['upload']['name'][$i];
if (move_uploaded_file($tmpFilePath, $filePath))
{
$files[] = $shortname;
$query = "insert into images(id,img_name) values('$file_id',' $filePath')";
mysqli_query($con, $query);
}
}
}
}
echo "<h1>Uploaded:</h1>";
if (is_array($files))
{
echo "<ul>";
foreach($files as $file)
{
echo "<li>$file</li>";
}
echo "</ul>";
}
}
?>
Table Images with attribute img_name type is LONGBLOB
now its totally working fine but when i am deleting image from database its getting error that image name is not found. here is code of sending image id and image name using a href
<ul>
<a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>"
style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
</a>
</ul>
now here is code of want i want to delete from my database and also from my localhost folder named img .
<?php
if (isset($_GET['img_id'], $_GET['img']))
{
$id = $_GET['img_id'];
$img = $_GET['img'];
$query = "delete from images where id='$id' and image='$img'";
if (mysqli_query($con, $query))
{
unlink($img);
echo '<script language="javascript">';
echo 'alert("Image Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("image does not exist")';
echo '</script>';
}
}
?>
now showing warning that img/image_name.jpg not found.Help me please .
I think your delete query is wrong
if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}
$query="delete from images where id='$id' and image='$img'";
In this query you check Id and Image field with same $id variable
try this :
<?php
if (isset($_FILES['image']['name'])) {
$name = $_FILES['image']['name'];
$tmpname1 = $_FILES['image']['tmp_name'];
$exten = explode(".", $_FILES['image']['name']);
$exten = $exten[1];
if ($exten != '') {
$image_name = "img" . time() . "." . $exten;
}
move_uploaded_file($tmpname1, FCPATH . 'assets/admin/uploads/' . $image_name);
$query = "insert into images(id,img_name) values('your_id',' $image_name')";
mysqli_query($con, $query);
//see your code
/*
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
*/
you pass the same id value for image. you should try this-
$query="delete from images where id='$id' and image='$img'";
}
I have made a blog for my website with PHP and mysql database, where I can add blog posts from an admin site (www.website.com/admin) and display them on my website (www.website.com). It's working fine, but I want to add pictures too.
This is my code for adding:
if (isset($_POST['submit'])) {
$blogtitle = htmlentities($_POST['blogtitle'], ENT_QUOTES);
$blogdate = htmlentities($_POST['blogdate'], ENT_QUOTES);
$blogdesc = htmlentities($_POST['blogdesc'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($blogtitle == '' || $blogdesc == '') {
$error = 'Please fill in all required fields';
renderForm($blogtitle, $blogdesc, $error);
} else {
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT blog_posts (blogtitle, blogdate, blogdesc) VALUES (?, ?, ?)")) {
$stmt->bind_param("sss", $blogtitle, $blogdate, $blogdesc);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: Could not prepare SQL statement.";
}
header("Location: website.php");
}
} else {
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
And my code for display the blog posts
/.../
while ($row = $result->fetch_object()) {
echo "<div>";
echo "<td>" . $row->blogtitle . "</td>";
echo "<td>" . $row->blogdate . "</td>";
echo "<td>" . $row->blogdesc . "</td>";
echo "</div>";
}
I know how to make an upload.php, but is it easier to upload to mysql? I dont know how to get the image shown in the right blogpost after uploading.
Best regards,
Tobias Dybdahl
You can upload the file to the server and then store the filename in your database, for example a column named "blogimg".
Then in your code for displaying blog posts you can add this line to show the image:
echo "<td><img src='" . $row->blogimg . "' /></td>";
you need to upload images to a directory and save images name in a database
after that right the url of the image in img tag and get the image name from the database
your html form
<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>
your php code
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I use this code to upload images in the database:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
And this code to display all images from the database:
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,'SELECT * FROM store');
while($row = $res->fetch_array()){
$image = $rows['image'];
echo "<img src='".$image."' />";
}
And I get something like tons of random symbols like diamonds with question marks in them and letters instead of my image. The scripts are not made by me. I just watched some tutorials and combined them and it seems that I didn't "combined" them properly. What am I doing wrong?
LATER EDIT:
HTML:
<img src="getImage.php?id=26"/>
PHP (getImage.php):
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM store WHERE id=$id");
while($row = mysql_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
Still can't get it to work! Help please!
I finaly did it!
This is the upload script:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = mysqli_real_escape_string($con,file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
Here is the diplay script:
$con = mysqli_connect('***', '***', '***', '***_dbimage');
$query = mysqli_query($con,"SELECT id FROM store");
while($row = mysqli_fetch_assoc($query))
{
$IDstore = $row['id'];
echo "<img src='getImage.php?id=".$IDstore."'/>";
}
And the "getImage.php":
<?php
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysqli_real_escape_string($con,$_GET['id']);
$query = mysqli_query($con,"SELECT * FROM store WHERE id=$id");
while($row = mysqli_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
I hope it will help someone cause it's ready to use now. :)
How can I show my all "blog post" with images? Example:
Mysql table:
post_id | user_id | subject | message | image | img_name.
What is the php code to display all my posts with images in the index page? I used the following code but it doesn't display images, it shows only data. I would like to see something like this:
image | message is here
image | message is here
image | message is here
I used 3 pages
add_post.php(Html form)
add_post_process.php(process the add_post.php)
index.php (which shows my all post)
add_post_process.php:
<?php
include "db.php";
#$file = addslashes($_FILES['image']['tmp_name']);
$lastid= mysql_insert_id();
#$img = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$img_name = addslashes($_FILES['image']['name']);
#$img_size = getimagesize($_FILES['image']['tmp_name']);
$upload_path = './blogpostimg/';
$post_id = addslashes($_POST['post_id']);
$user_id = addslashes($_POST['user_id']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
$cat_id = addslashes($_POST['cat_id']);
$cat_name = addslashes($_POST['cat_name']);
$comment_count = addslashes($_POST['comment_count']);
$ch_img = addslashes($_FILES['image']['name']);
$query = "SELECT img_name FROM blog_post WHERE img_name = '$ch_img';";
$result = mysql_query($query) or die (mysql_error());
if(isset($subject, $message))
{
$errors = array();
if(empty($subject) && empty($message) && empty($file))
{
$errors[] ='all field required';
}
else
{
if(empty($subject))
$errors[] = 'Subejct requried';
if (empty($message))
$errors[] = 'message required';
if(empty($file))
$errors[] ="SORRY, you have to be upload a image";
elseif($img_size == FALSE)
{
$errors[] ="That's not an image";
}
else
{
if(mysql_num_rows($result) != 0)
$errors[] = " You have to change this image name, already exit in our database";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo "<ul>";
echo "<strong><font color=red><li>$error</li></font></strong><br/>";
echo "</ul>";
}
}
else
{
if(!move_uploaded_file($_FILES['image']['tmp_name'],$upload_path . $img_name))
{
die('File Not Uploading');
}
else
{
$lastid = mysql_insert_id();
$query = mysql_query("INSERT INTO blog_post VALUES ('', '', '$subject',
'$img','$img_name','$message','$cat_id','$cat_name','',NOW() )");
if($query)
echo "Successfully uploaeded your post";
else
{
echo "Something is wrong to Upload";
}
}
}
}
?>
index.php
<?php
include "db/db.php";
$upload_path = "/secure/content/blogpostimg";
$sql= mysql_query("SELECT * FROM blog_post");
while ($rel = mysql_fetch_assoc($sql))
{
$id = $rel['post_id'];
$sub = $rel['subject'];
$imgname = $rel['img_name'];
$img = $rel ['image'];
$msg = $rel['message'];
$date = $rel['date'];
echo "<h1>". "$sub" ."</h1>". "<br/>";
echo "$imgname" ."<br/>";
echo '<img src="$upload_path " />';
echo "$msg" . "<br/>";
echo "$date" . "<br/>";
echo "<hr/>";
echo "<br/>";
}
?>
The mysql table structure is
post_id(int)
User_id(int)
subject(varchar)
image(blob)
img_name(varchar)
message(text)
change
echo '<img src="$upload_path " />';
to
echo '<img src="' . $upload_path . '/' . $img . '" />';
that should do the trick..
I don't now if it matters in performanceways.. but howcome you use blob instead of a varchar.. 255 characters for a filename should be enough.
In your index.php you have <img src="$upload_path" />. Instead of $upload_path, src needs to be the URL to your image.
I just noticed that you are storing the image itself in the database. There is no need to do this if you move it to a publicly accessible directory, e.g. /var/www/images/myimage.jpg