How to delete image from two different database and folder with PHPMYSQL - php

// i have two tables like,projects and projectfiles.
projects fields are:
id,name,alice,catg,img;
//insertin the image in the folder 'upload'
projectfiles fields are :
id,name,img
//inserting the image in the folder 'image'
so,how delete the data from projects and projectfiles even from directory.
<?php
include('dbconfig1.php');
if(!$db)
{
die(mysqli_error());
}
$sql = "select * from projects";
$result = $db->query($sql);
if(isset($_GET['id']))
{
$selectSql = "select * from projects where id = ".$_GET['id'];
$rsSelect = mysqli_query($db,$selectSql);
$getRow = mysqli_fetch_assoc($rsSelect);
$getIamgeName = $getRow['img'];
$createDeletePath = "upload/".$getIamgeName;
if(unlink($createDeletePath))
{
$deleteSql = "delete from projects where id = ".$getRow['id'];
$rsDelete = mysqli_query($db, $deleteSql);
if($rsDelete)
{
header('location:projects.php?success=true');
exit();
}
}
else
{
$errorMsg = "Unable to delete Image";
}
}
?>
?>
<?php
if(isset($_GET['success']) && $_GET['success'] == 'true')
{
?>
<div class="alert alert-success">
<?php
echo "Images has been deleted sucessfully";
?>
</div>
<?php
}
?>

Related

Image isn't updating in mysql database

So i have the following scripts:
<?php
//Posts variables
$post_id = 0;
$isEditingPost = false;
$published = 0;
$title = "";
$post_slug = "";
$body = "";
$featured_image = "";
$post_topic = "";
//Get all posts
function getAllPosts(){
global $conn;
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
}elseif($_SESSION['user']['role'] == "Author"){
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn,$sql);
$posts = mysqli_fetch_all($result,MYSQLI_ASSOC);
$final_posts = array();
foreach($posts as $post){
$post['author'] = getPostAuthorById($post['user_id']);
array_push($final_posts,$post);
}
return $final_posts;
}
function getPostAuthorById($user_id){
global $conn;
$sql = "SELECT username FROM users WHERE id=$user_id";
$result = mysqli_query($conn,$sql);
if($result){
return mysqli_fetch_assoc($result)['username'];
}else{
return null;
}
}
/* - - - - - - - - - -
- Post actions
- - - - - - - - - - -*/
// if user clicks the create post button
if (isset($_POST['create_post'])) { createPost($_POST); }
// if user clicks the Edit post button
if (isset($_GET['edit-post'])) {
$isEditingPost = true;
$post_id = $_GET['edit-post'];
editPost($post_id);
}
// if user clicks the update post button
if (isset($_POST['update_post'])) {
updatePost($_POST);
}
// if user clicks the Delete post button
if (isset($_GET['delete-post'])) {
$post_id = $_GET['delete-post'];
deletePost($post_id);
}
/* - - - - - - - - - -
- Post functions
- - - - - - - - - - -*/
function createPost($request_values)
{
global $conn,$user_id, $errors, $title, $featured_image, $topic_id, $body, $published;
$user_id = $_SESSION['user']['id'];
$title = esc($request_values['title']);
$body = htmlentities(esc($request_values['body']));
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
if (isset($request_values['publish'])) {
$published = esc($request_values['publish']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
// validate form
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
if (empty($topic_id)) { array_push($errors, "Post topic is required"); }
// Get image name
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) { array_push($errors, "Featured image is required"); }
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
// Ensure that no post is saved twice.
$post_check_query = "SELECT * FROM posts WHERE slug='$post_slug' LIMIT 1";
$result = mysqli_query($conn, $post_check_query);
if (mysqli_num_rows($result) > 0) { // if post exists
array_push($errors, "A post already exists with that title.");
}
// create post if there are no errors in the form
if (count($errors) == 0) {
$query = "INSERT INTO posts (user_id, title, slug, image, body, published, created_at, updated_at) VALUES($user_id, '$title', '$post_slug', '$featured_image', '$body', $published, now(), now())";
if(mysqli_query($conn, $query)){ // if post created successfully
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
}
/* * * * * * * * * * * * * * * * * * * * *
* - Takes post id as parameter
* - Fetches the post from database
* - sets post fields on form for editing
* * * * * * * * * * * * * * * * * * * * * */
function editPost($role_id)
{
global $conn, $title, $post_slug, $body, $published, $isEditingPost, $post_id;
$sql = "SELECT * FROM posts WHERE id=$role_id LIMIT 1";
$result = mysqli_query($conn, $sql);
$post = mysqli_fetch_assoc($result);
// set form values on the form to be updated
$title = $post['title'];
$body = $post['body'];
$published = $post['published'];
}
function updatePost($request_values)
{
global $conn, $errors, $post_id, $title, $featured_image, $topic_id, $body, $published;
$title = esc($request_values['title']);
$body = esc($request_values['body']);
$post_id = esc($request_values['post_id']);
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
// if new featured image has been provided
if (isset($_POST['featured_image'])) {
// Get image name
$featured_image = $_FILES['featured_image']['name'];
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
}
// register topic if there are no errors in the form
if (count($errors) == 0) {
$query = "UPDATE posts SET title='$title', slug='$post_slug', views=0, image='$featured_image', body='$body', published=$published, updated_at=now() WHERE id=$post_id";
// attach topic to post on post_topic table
if(mysqli_query($conn, $query)){ // if post created successfully
if (isset($topic_id)) {
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
$_SESSION['message'] = "Post updated successfully";
header('location: posts.php');
exit(0);
}
}
// delete blog post
function deletePost($post_id)
{
global $conn;
$sql = "DELETE FROM posts WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = "Post successfully deleted";
header("location: posts.php");
exit(0);
}
}
// if user clicks the publish post button
if (isset($_GET['publish']) || isset($_GET['unpublish'])) {
$message = "";
if (isset($_GET['publish'])) {
$message = "Post published successfully";
$post_id = $_GET['publish'];
} else if (isset($_GET['unpublish'])) {
$message = "Post successfully unpublished";
$post_id = $_GET['unpublish'];
}
togglePublishPost($post_id, $message);
}
// delete blog post
function togglePublishPost($post_id, $message)
{
global $conn;
$sql = "UPDATE posts SET published=!published WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = $message;
header("location: posts.php");
exit(0);
}
}
?>
Everything works fine , it updates the topic , the post body,title,published state but the image isn't updating , even tho when i create a new post the image is being inserted in the database , when i try to update , the image column in database remains empty.
Here is the create_post.php
<?php include('../config.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/admin_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/post_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/header.php'); ?>
<!-- Get all topics -->
<?php $topics = getAllTopics(); ?>
<title>Admin | Create Post</title>
</head>
<body>
<!-- admin navbar -->
<?php include(ROOT_PATH . '/admin/includes/navbar.php') ?>
<div class="container content">
<!-- Left side menu -->
<?php include(ROOT_PATH . '/admin/includes/menu.php') ?>
<!-- Middle form - to create and edit -->
<div class="action create-post-div">
<h1 class="page-title">Create/Edit Post</h1>
<form method="post" enctype="multipart/form-data" action="<?php echo BASE_URL . 'admin/create_post.php'?>">
<?php include(ROOT_PATH . '/includes/errors.php') ?>
<?php if($isEditingPost == true):?>
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<?php endif ?>
<input type="text" name="title" value="<?php echo $title; ?>" placeholder="Title">
<label style="float: left; margin: 5px auto 5px;">Featured image</label>
<input type="file" name="featured_image">
<textarea name="body" id="body" cols="30" rows="10"><?php echo $body; ?></textarea>
<select name="topic_id">
<option value="" selected disabled>Choose topic</option>
<?php foreach ($topics as $topic): ?>
<option value="<?php echo $topic['id']; ?>">
<?php echo $topic['name']; ?>
</option>
<?php endforeach ?>
</select>
<?php if($_SESSION['user']['role'] == 'Admin'):?>
<?php if($published == true):?>
<label for="publish">
Publish
<input type="checkbox" value='1' name="publish" checked="checked">
</label>
<?php else:?>
<label for="publish">
Publish
<input type="checkbox" value="1" name="publish">
</label>
<?php endif ?>
<?php endif ?>
<?php if ($isEditingPost === true): ?>
<button type="submit" class="btn" name="update_post">UPDATE</button>
<?php else: ?>
<button type="submit" class="btn" name="create_post">Save Post</button>
<?php endif ?>
</form>
</div>
</body>
</html>
<script>
CKEDITOR.replace('body');
</script>
I think the problem might be with your if statement in updatePost function if (isset($_POST['featured_image'])) {. Change this like in createPost function
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) {
...
}
Check also https://www.php.net/manual/en/features.file-upload.post-method.php for more information about checking uploaded files.

cant see image from avatar_path

i am storing image in uploads folder an then in a random directory but it is not being shown in my website this is my code
<?php
$query = "SELECT * FROM users WHERE email='$email' or username = '$email'or mobile='$email'";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
$users = mysqli_fetch_assoc($fire);
}
?>
<img src="<?php echo $users['avatar_path']?>" width='100' height='100' class='avatar'>
and this is my upload code
if (isset($_POST['uploadimg'])) {
$avatar = $_FILES['avatar'];
$avatar_name = $_FILES['avatar']['name'];
$avatar_tmpname = $_FILES['avatar']['tmp_name'];
$avatar_size = $_FILES['avatar']['size'];
$avatar_type = $_FILES['avatar']['type'];
$avatar_ext = pathinfo($avatar_name, PATHINFO_EXTENSION);
if (!empty($avatar_name)) {
if ($avatar_size <= 25000000) {
if ($avatar_ext == "jpg" || $avatar_ext == "jpeg" ||$avatar_ext == "png" ) {
$chars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name=substr(str_shuffle($chars),0,15);
mkdir("uploads/$rand_dir_name");
$final_file= "uploads/$rand_dir_name/$avatar_name";
$upload = move_uploaded_file($avatar_tmpname, $final_file);
if ($upload) {
unlink("$avatar_path");
$msg = "file uploaded successfully ";
$query = "UPDATE users SET avatar_path='$final_file' WHERE id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE likes SET avatar_path='$final_file' WHERE user_id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE photos SET avatar_path='$final_file' WHERE uid='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
if ($fire) {
$msg .=" and also inserted into database";
}
# code...
}else{ echo "only jpg,jpeg,png, type format allowed";}
}else{echo "file size is too large";}
}else{echo "please select an image to upload";}
}
}
}
?>
this code used to work on localhost and my upload code is still working and when i inspect my page the avatar path is correct but still the pic is not being shown a broken image is shown i dont know what is being wrong this is the avatar path that is coming
uploads/Un7sL9TwyNzOhco/bhai.jpg
Try adding slash at first like below:
$final_file= "/uploads/$rand_dir_name/$avatar_name";

error in function follow /unfollow users

hi am working on a script to allow users to follow each other but the action.php file to do the work is giving me a headache or maybe i don't know what and where i a have gone wrong i have 3 functions
-check_count checks if the user is already following another user
-follow_user executes the follow a user query
-unfollow_user executes the unfollow user query
then, i have the action php file that gets ids from the follow and unfollow links
//home page
<div class="panel panel-default">
<div class="panel-body">
<?php
$users = show_users();
$following = following($_SESSION['login']);
if (count($users)){
foreach ($users as $key => $value){
echo $key," ", $value;
if(in_array($key, $following)){
echo " <small><a href='action.php?id=$key&do=unfollow'>unfollow</a> </small>","<br>";
}else{
echo " <small><a href='action.php?id=$key&do=follow'>follow</a> </small>","<br>";
}
}
}else{
echo "<p>","<b>","There are no users in the system","<b>","<p>";
}
?>
</div>
</div>
//action .php file
<?php
session_start();
//session variables goes down here
include_once('includes/dbconnect.php');
include_once('functions.php');
$id = $_GET['id'];
$do = $_GET['do'];
switch ($do){
case "follow":
follow_user($_SESSION['login'],$id);
$msg = "You have followed a user!";
break;
case "unfollow":
unfollow_user($_SESSION['login'],$id);
$msg = "You have unfollowed a user!";
break;
}
$_SESSION['message'] = $msg;
header("Location:home.php");
?>
//the functions
function check_count($first,$second){
global $conn;
$sql="SELECT COUNT(*) FROM following WHERE fuser_id='$second' AND follower_id='$first'";
$result=mysqli_query($conn,$sql);
$row = mysql_fetch_row($result);
return $row[0];
}
function follow_user($me,$them){
global $conn,$id;
$count = check_count($me,$them);
if($count==0){
$sql="INSERT INTO following (fuser_id,follower_id) VALUES($them,$me)";
$result=mysqli_query($conn,$sql);
}
}
function unfollow_user($me,$them){
global $conn,$id;
$count = check_count($me,$them);
if($count !=0){
$sql="DELETE FROM following WHERE fuser_id='$them' and follower_id='$me' limit 1";
$result=mysqli_query($conn,$sql);
}
}

PHP if statement within if statement

I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>

Why wont my PHP MYSQL comparison work

Im messing around, trying to see if i can make one of those clickable pet sites that were all the rage a couple years ago and i run into a problem with trying to use if, else, elseif stuff in PHP.
Heres what I have:
<?php
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
if ($tempclicks == 150) {
mysql_query("UPDATE sitefunctions SET `level` = 2 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
elseif ($tempclicks == 600) {
mysql_query("UPDATE sitefunctions SET `level` = 3 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='index'");
while($row = mysql_fetch_array($sql)){
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
};
if ($level == 1) {
$imageu = $image1;
}
elseif ($level == 2) {
$imageu = $image2;
}
elseif ($level == 3) {
$imageu = $image3;
}
?>
<html>
<head>
</head>
<body>
<p>
<?php print $oldip; ?> <br>
<?php print $newip; ?> <br>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
<?php print $message; ?>
</p>
</body>
</html>
Now the first problem i'm having is with comparing the users ip with the last ip that was on the page.
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
No matter what i have tried it doesnt really compare the values. If i put a "=" it says theyre the same no matter what and if i do "==" it says theyre different even though they shouldn't be.
I dont even know where to start with this, no errors come up and i'm fairly new to PHP and MYSQL. Nothing else can be really tested until this, but im sure that the rest of the comparisons dont work either.
im using 000webhost for my site, if thats known to have problems lol
This is what my code looks like now, it works too so im done here:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
$name = $_POST['name'];
if (empty($name) == true){
$name = "index";
};
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$lastip = $row["lastip"];
}
if ($lastip == $newip) {
$message = "You were the last one to click this pet! You have to wait until someone else clicks it!";
} else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='$name'") or die(mysql_error());
$message = "You clicked the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
}
if ($clicks > 50*$level) {
mysql_query("UPDATE sitefunctions SET `level` = `level`+1 WHERE name='$name'") or die(mysql_error());
$message = "Your click leveled up the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
$lastip = $row["lastip"];
};
if ($level > 35) {
$imageu = $image3;
} elseif ($level > 15) {
$imageu = $image2;
} elseif ($level > 0) {
$imageu = $image1;
};
?>
<html>
<head>
</head>
<body>
<center>
<p>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
Last User: <?php print $lastip; ?> <br>
<?php print $message; ?>
</p>
</center>
</body>
</html>

Categories