delete image from path and database - php

I am getting the following errors:
Warning: unlink() [function.unlink]: Invalid argument in
C:\xampp\htdocs\SH\owner\delete_img.php
on line 11
and
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
'* FROM img_homestay WHERE imgid='"73"'' at line 1
This is my code for delete image. My images have own imgid. I want to delete it using their imgid.
<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($img['location']);
$result=mysql_query("DELETE * FROM img_homestay WHERE imgid='$imgid'")
or die(mysql_error());
header("Location: editimage1.php");
?>
This is the link of one of the pictures I want to delete:
/SH/owner../data/img1.jpg

From the comment. It's been edited.
Your query should be DELETE FROM. Remove the * from your query.
The full query: DELETE FROM img_homestay WHERE imgid='$imgid'
Also, you can either remove the $result = part from your query, or do this.
if($result) {
//Successfully deleted image.
}
Also, your code is highly susceptible to SQL injection. You are passing in raw user input into your SQL query. At the very least, you should be escaping out quotations, but it is highly recommended that you also use the MYSQLI or PDO set of functions for database connections and queries.
You may also need to need check your permissions for the folder that you are trying to remove the file from. Ideally, folders which house images should be set to chmod 755.
http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/
This link is a very basic introduction to prepared statements, and also provides links for further reading.
EDIT: Full snippet.
<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
$imgid = mysql_real_escape_string($imgid);
$path= $_SERVER['DOCUMENT_ROOT'].'/owner../data/';
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($path.$img['location']);
$result=mysql_query("DELETE FROM img_homestay WHERE imgid='$imgid'") or die(mysql_error());
//Check to see if the query can run
if($result) {
header("Location: editimage1.php");
} else {
//Query failed. Display an error message here.
}
?>

<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
$path= $_SERVER['DOCUMENT_ROOT'].'/owner../data/';
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($path.$img['location']);
$result=mysql_query("DELETE FROM img_homestay WHERE imgid='$imgid'") or die(mysql_error());
header("Location: editimage1.php");
?>

This type of error basically needs debugging.
First check whether problem is related to unlink() function or in Sql connectivety.
Create another php file n check whether its working for static path
<?php
$path='/SH/owner../data/img1.jpg'; // update it as per your filepath..path should be from root
if(unlink($path))
{
echo "Deleted file ";
}
else
{
echo "Not Able to Delete File";
}
?>
Lets see what it retruns.
As Part Written by 9997 regarding database connection and query execution seems perfectly fine.

Related

I am trying to store form information in a mysql database but it does not foward to the database

So I have a form and the form action= the file that contains the code below. I am getting a connection but the data is not saving. I formatted my form with input type textarea and the database with long text because I want to give the user as much space as they need to write their information. I think this might be my issue and have been searching the web to see if it is but I can't find anything that says it is or not. The weird part is that one time i did see an increase in the row of the database but when I checked it the row didn't contain the info I sent, it was blank.
<?php
session_start();
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ='0')
{header('location:shareerror.php');}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
header ('location:thanks.php'); }
?>
By mistake you are assigning instead of checking corrected statement is:
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ==0)
There is an error in your query
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
change this to
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
You are not setting the values for $recipe, $usrtext and $usrtxt
You are missing a comma in the values.
You are using strlen instead of isset
Also please take a look at How can I prevent SQL injection in PHP?. Your code is vulnerable to sql injection.
Here is the fixed code (with sql injection vulnerability intact!!)
<?php
session_start();
if (!isset($_POST['recipe'])|| !isset($_POST['usrtext'])||!isset($_POST['usrtxt']))
{
header('location:shareerror.php');
}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$usrtxt = $_POST['usrtxt'];
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext','$usrtxt')");
header('location:thanks.php');
}
?>
Also you didn't assign the variables used in the query.
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
do that like this:
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$urstxt = $_POST['usertxt'];
Then you can use the variables in the query

Error:NO database is selected

I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function

PHP unlink() not working to delete files

I am have been trying to setup this code to delete a row on the mysql database as well as the photo that was uploaded with it. It is working GREAT to remove the row data, but it will not get rid of the photo, and I cannot figure out what I am doing wrong. To simplify things, im using the variable $id which is the number of the row entered in the form which triggers this php file:
<?php
$host="localhost"; // Host name
$username="blahblah_plans"; // Mysql username
$password="password"; // Mysql password
$db_name="blahtbl_name"; // Database name
$tbl_name="plans"; // Table name
// Connect to server and select databse.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['idnum'];
$compositesql="SELECT composite FROM plans WHERE ID ='$id'";
$compositeresult = mysql_query($compositesql) or die(mysql_error());
$compositefilename = "/composite/" + $compositeresult;
$unlink = unlink($compositefilename);
if($unlink) {
echo 'Successfully deleted file: ';
echo $compositefilename;
} else {
echo 'Error deleting file: ';
echo $compositefilename;
}
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE ID ='$id'";
$result = mysql_query($sql);
if($result){
header("location:planentry.php");
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Make sure the path is right, $compositefilename = "/composite/" + $compositeresult; should be the path in the server, it most likely to be
$compositefilename = PATH_TO_YOUR_WEB_ROOT . "/composite/" . $compositeresult;
And php does not use + to concat strings.
The problem is that $compositeresult contains a resource rather than a result set. This line is what's causing it:
$compositeresult = mysql_query($compositesql) or die(mysql_error());
To fix that, store the resource on a variable, then store the result set on another variable, like this:
$compositequery = mysql_query($compositesql) or die(mysql_error());
$compositeresult = mysql_fetch_array($compositequery) or die(mysql_error());
Also, I highly recommend that you start using mysqli or PDO instead of mysql, since it's safer. Also, as xdazz said, PHP's concatenation operator is the dot, not the plus sign. So your $compositefilename should be declared as (note that $compositeresult is an array of data and therefore should have its correct key explicitly written):
$compositefilename = "/composite/" . $compositeresult['composite'];

PHP SQL Truncate

I'm having a problem trying to truncate the 'requestID' field from my requests table.
This is my code.
<?php
include 'mysql_connect.php';
USE fypmysqldb;
TRUNCATE TABLE requestID;
echo "Request ID table has been truncated";
?>
I'm using server side scripting so no idea what error is coming back.
Anyone got an idea?
You aren't executing queries, you're just putting SQL code inside PHP which is invalid. This assumes you are using the mysql_*() api (which I kind of suspect after viewing one of your earlier questions), but can be adjusted if you are using MySQLi or PDO.
// Assuming a successful connection was made in this inclusion:
include 'mysql_connect.php';
// Select the database
mysql_select_db('fypmysqldb');
// Execute the query.
$result = mysql_query('TRUNCATE TABLE requestID');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysql_error();
Take a look at the function mysql_query which performs the query execution. The code to execute a query should look something like this.
$link = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db("fypmysqldb", $link) or die(mysql_error());
mysql_query("TRUNCATE TABLE requestID", $link) or die(mysql_error());
mysql_close($link);

PHP Resource ID error

I want to retrieve or output data in the database but I kept on getting the error called "Resource ID".
Here is my code:
<?php
$host="localhost";
$username="root";
$password ="123192";
$db_name = "customers";
//Connecting to your Host
mysql_connect("$host","$username","$password") or die("Failed To Connect The server");
//Selecting your Database
mysql_select_db("$db_name") or die("Failed To Select The DB");
$name = $_REQUEST['customerName'];
echo 'WELCOME! <b>'.$name.'</b> We hope that you\'ll Enjoy your stay ';
$sql="SELECT Name FROM `people` WHERE id =2 && Name = 'Kyel'";
$rs=mysql_query($sql);
echo "$rs";
?>
If I need improvement regarding my code kindly tell me.
mysql_query() returns a resource. The to string (implicitly triggered by using echo to output it) of that is Resource ID # followed by the id.
A resource in PHP is only supposed to be used with other PHP functions. This includes but is not limited to file, curl, ftp handles, etc.
I could tell you to..
(a) use mysql_fetch_array() (or similar) or
(b) use PDO.
The latter is by far much better advice.
Try this instead of the echo statement:
$array = mysql_fetch_assoc($rs);
var_dump ($array);

Categories