delete photo script gives errors in php and mysql - php

hi guys im trying to create a ajax delete script for my gallery but it doesn't seem to be deleting, instead it gives the following errors.
Warning: Division by zero in /opt/lampp/htdocs/project/others/delete_photo.php on line 20
Warning: unlink(): No such file or directory in /opt/lampp/htdocs/project/others/delete_photo.php on line 20
the delete script is as follows:
<?php
require $_SERVER["DOCUMENT_ROOT"].'/project/includes/dbconfig.inc.php';
$session= htmlentities($_SESSION['uname']);
$sess_uname= stripslashes($session);
$id0= htmlentities($_POST['id']);
$id= stripslashes($id0);
$sql="DELETE FROM photos WHERE id=':id' LIMIT 1";
$stmt=$conn->prepare($sql);
$stmt->bindparam(":id",$id);
$stmt->execute();
$sql1 = "SELECT * FROM photos WHERE user=':session' LIMIT 30";
$stmth=$conn->prepare($sql1);
$stmth->bindparam(":session",$sess_uname);
$stmth->execute();
$dir="user/$sess_uname";
$count0=$stmth->fetch(PDO::FETCH_ASSOC);
$count=count($count0);
$row1 = $stmth->fetch(PDO::FETCH_ASSOC);
if ($count>0) {
unlink($dir/$row1['filename']);
}
/*if (isset($_SESSION['app'])&&$_SESSION['uname']!="") {
header("location: ../home.php?u={$_SESSION['uname']}");
} else {
header("location: ../index.php?usernotfound?id=017");
}
*/
the ajax logic is as follows:
$("button.delete_photo").click(function(){
var del_id = $(this).attr('id');
var del_attr=$(this).attr('attr');
$.post("others/delete_photo.php",
{id:del_id},function(data){
$("."+del_id).slideUp('slow', function() {$(this).remove(data);});
}
);
});

Starting from the very beginning:
1)
echo this and see what you get? Are you getting the desired/expected name?
echo $session= htmlentities($_SESSION['uname']);
If so, echo this as well:
$sess_uname= stripslashes($session);
2) Similarly, if you're getting a expected result by echoing from:
$id0= htmlentities($_POST['id']);
This means your first query should work.
Now, the query below works if you have already got a expected result from 1)
$sql1 = "SELECT * FROM photos WHERE user=':session' LIMIT 30";
3) This is not the correct way to assign a directory.
$dir="user/$sess_uname";
Rather use the proper concatenation like:
$dir= "user" . "/" . $sess_uname;
4) If for all that works above, this is also incorrect. Either use $_SERVER['DOCUMENT_ROOT'] to construct absolute paths beginning with the root of your website, or else use relative paths, The line written below is the reason you're getting the Warning: Division by zero:
unlink($dir/$row1['filename']);
Which rather should have been:
unlink($dir . "/" . $row1['filename']);
But that is only if $row1 is working, which at the moment clearly is not.

Change this line
unlink($dir/$row1['filename']);
to
unlink($dir.'/'.$row1['filename']);
Because instead of providing directory structure, you are dividing the value.

finally found the solution, the problem was with the sql syntax.
previously it was like:
$sql="DELETE FROM photos WHERE id=':id' LIMIT 1";
$sql1 = "SELECT * FROM photos WHERE user=':session' LIMIT 30";
i took out the single quotes for id as it was an integer and now it works like a charm.
now my code looks like this:
$sql="DELETE FROM photos WHERE id=:id LIMIT 1";
$sql1 = "SELECT * FROM photos WHERE id=:id LIMIT 1";

Related

Sql like query with variable?

I have this function:
function word($arg){
echo ''.$arg.'';
//echoes test
require ('config.php');
$requestSQL = mysql_query("SELECT * FROM db where eng LIKE '%$arg%' order by id ASC LIMIT 10", $connection);
while ($row = mysql_fetch_array($requestSQL))
{
echo ''.$row['id'].': '.$row['eng'].'<br>';
}
}
Gets triggered by:
$number = $explode[1];
word($number);
But doesn't echo values from the database, nothing at all.
If I echo $arg (in the function), it shows the value. If I replace in my sql query: '%$arg%' with '%test%', it echoes the correct value.
Is the '%$arg%' syntax wrong?
You should use a proper concat
"SELECT * FROM db where eng LIKE concat('%', '$arg', '%') order by id ASC LIMIT 10"
It's pretty simple, all you do is: LIKE %{$arg}%. Because I am assuming that $arg is a text value. If a variable is a text value then you must do this to keep it working. You wrap text variables in {}.
Also, never . . . EVER use mysql_*, you should move to mysqli_* or PDO/OOP. It's just good practice.
Update
You can't use variables within mysql_query("", $connection) quotes. Instead, do this:
$query = "SELECT * FROM db WHERE eng LIKE '%{$arg}%' ORDER BY id ASC LIMIT 10";
// then use this variable as a replacement for the quotes in the mysql_query().
$set = mysql_query($query, $connection); // like so . . .
// mysql_fetch_assoc() is the same as mysql_fetch_array().
while($row = mysql_fetch_assoc($set)) {
echo "".$row['id'].": ".$row['eng']."<br>";
}
I'm so stupid, actually $explode[1]; was returning the correct value but had a blank line in the source code. So I had to use trim and now it works.

Error unterminated string literal when using php mysql?

I have a this code:
$sql = "SELECT * FROM news order by id DESC LIMIT 10";
$data = array();
$query = mysql_query($sql);
if(!$query) {
echo "Error: " . mysql_error();
exit;
}
while($row = mysql_fetch_object($query)) {
$data[] = $row;
}
return $data;
When I run code, result OK, But when I repair limit from 10 to limit 15 or more is error is unterminated string literal
$sql = "SELECT * FROM news order by id DESC LIMIT 15"; // limit 15, 20 or more
Really? I don't mean to sound condescending but are you absolutely sure that you're not overwriting the " when you change that 10 to a 15?
Because there nothing in that code that indicates unbalanced quotes. Failing that, there may be a problem earlier on in the code (though, of course, we can't see it).
I would suggest you cut and paste the exact code that's causing the problems.
This the type of error you need to separate from your main code base.
create a simple test php script that connects to the database and executes the query.
does that work? if not, create a small sample database and test on that.
if that fails, then post the create table statement along with insert statements. also post your code. odds are you're doing something else in the main code base that is causing the error.
if your sample code does work and your main codebase does, then you have to trace through your main code base and find out what you're doing wrong.

php counter increment error

As i am trying to increment the counter to plus 1 every time when the user clicks on the image. I have written the following code but it says some error "Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tkboom\includes\core.php on line 72". Can anyone look into this where i made a mistake..
Actually i have created 2 php files one for incrementing the counter and one for displaying the counter. In core.php file i have written the function and for displaying the count i have created a file called view.php
core.php
function GenerateCount($id, $playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = $counter_row['hits'] + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
view.php
<?php
$sql = mysql_query("SELECT * FROM ava_games WHERE published=1 ORDER BY id desc LIMIT 30");
while($row = mysql_fetch_array($sql)) {
$url = GameUrl($row['id'], $row['seo_url'], $row['category_id']);
$name = shortenStr($row['name'], $template['module_max_chars']);
$playRt = GenerateRating($row['rating'], $row['homepage']);
$playCt = GenerateCount($row['id'], $row['hits']);
if ($setting['module_thumbs'] == 1) {
$image_url = GameImageUrl($row['image'], $row['import'], $row['url']);
$image = '<div class="homepage_game"><div class="home_game_image"><img src="'.$image_url.'" width= 180 height= 135/></div><div class="home_game_info"><div class="home_game_head">'.$name.'</div></div><div class="home_game_options"><img class="home_game_options_icon" src="'.$setting['site_url'].'/templates/hightek/images/joystick-icon.png" /> '.$playRt.' <b>|</b> '.$playCt.' plays </div></div>';
echo $image;
}
}
?>
That most likely means that there's an error in the sql statement. You can get more information about the error via mysql_error().
In its simplest form:
$counter_res = mysql_query($counter_query) or die(mysql_error());
(edit: ...simplest form, but with this approach you don't give the application a chance to react to the problem, "die" as in "dead". And mysql_error() can leak too much information to a user of your webservice/website, see https://www.owasp.org/index.php/Top_10_2007-Information_Leakage_and_Improper_Error_Handling)
Your code is also prone to
sql injections, because the $_GET parameter is put into the statement without sanitizing it first
race conditions because you have a compound operation consisting of one SELECT and one UPDATE without any locking mechanism.
This is because you get the error in your SQL query.
I'd change it a little bit:
$counter_query = 'SELECT hits FROM ava_games WHERE id = ' . (int)$_GET['id'];
to make sure you always compare id against integer value.
After all, this query does not look good. First point: why are you using two queries to increment a value? UPDATE ava_games SET hits=hits+1 WHERE id=".$_GET['id'].""should do this in one step. Second point: have you heard about SQL injections? Escape or cast $_GET['id'] to avoid surprises ;)
Convert the value in int first like that:
function GenerateCount($playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = intval($counter_row['hits']) + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
and check link:
Convert into int
If mysql_query returns a Boolean, your query failed.
Presuming id is the primary key, you can use the following function to update on a database level which will prevent race conditions:
function GenerateCount($playCount) {
global $setting;
$update_counter_query = "UPDATE ava_games SET hits=hits + 1 WHERE id=".intval($_GET['id'])."";
mysql_query($update_counter_query) or die(mysql_error());
$counter_query = "SELECT hits FROM ava_games WHERE id=".intval($_GET['id'])." LIMIT 1";
list($playCount) = mysql_fetch_row(mysql_query($counter_query));
return $playCount;
// Get count END
}
also note the intval() around the $_GET variable to prevent SQL injection

MySQL Delete Item from Table not working

I am trying to delete a record in my db based on the unique id ($id). Is there something wrong with this code? Probably a simple one for you php pro's.
function delAccount(){
mysql_query("DELETE FROM accounts WHERE id=".$id."LIMIT 1");
}
I get a :
Fatal error: Can't use function return value in write context in
/home/content/53/7311353/html/cca/accounts/include/processAct.php on line 15
My Class that I have powering everything:
class Accounts
{
function Accounts(){
if (isset($_POST['addacct'])){
$this->addAccount();
}elseif(isset($_POST['editacct'])){
$this->editAccount();
}elseif(isset($_POST['delacct'])){
$this->delAccount();
}else{
// redirect if loaded without a POST value set
header("Location: ../index.php?o=illegal&t=nodata");
}
}
You should, first of all, put a space between ".$id." and LIMIT so:
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
Secondly, the $id is NOT available within this function by default. Either do this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
and use delAccount($id_parameter); in your script to send the ID along with the function. Or try this:
function delAccount() {
global $id;
mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
}
then you can call this function after you set the value of $id somewhere else in your code.
First: is the value for $id actually an id in the database? Second you need a space before "LIMIT", ie:
" LIMIT 1".
Are you sure $id is set?
If $id should be sent to the function as an argument, try this:
function delAccount($id) {
mysql_query("DELETE FROM accounts WHERE id=" . $id . " LIMIT 1");
}
EDIT: You missed a space character between the ID and the LIMIT.
Added some small improvements to the form of the query string:
function delAccount($id) {
mysql_query("DELETE FROM `accounts` WHERE `id` = " . $id . " LIMIT 1");
}
EDIT:
The error you get doesn't come from MySQL itself. Have you checked the returned value. It might return another error, or the returned value might be correct, but used in an erroneous way in later code.
Your error is from the PHP compiler. Are you doing something like this on line 15:
if (delAccount(...) = false) { ... }
? If so, change to ==.
Some hints on how to debug stuff like this.
If you suspect something is wrong, the first thing to do is to output the generated query. Like so:
$query = "DELETE FROM accounts WHERE id=".$id."LIMIT 1";
echo $query; // for debugging
That will show you that at least one thing is wrong with your query: You have a space missing before LIMIT.
mysql_query() returns false if it encounters an error. You can check for that, and output it using mysql_error(). Like so:
$result = mysql_query($query);
if(!$result) trigger_error("Database error!: ".mysql_error());
If $id comes from outside, like the $_GET array, make sure you have tested whether it is an integer before using it in a query to avoid SQL injection.

mysql php where clause not working

Any ideas why this wouldnt work!?
Just nothing displays..
$result1 = mysql_query("select * from `suppliers` where supp_short_code='WED'") or die(mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo "<p>" . $row1['supp_name'] . "</p>";
}
Resolved! turns out when i imported from Excel to my mysql in brought in spaces after and before the "supp_short_code" so the query wasnt working!
Is 'supp_name' a column of your 'suppliers' table?
Does this query return any result under phpmyadmin eg?
Are the <p> tags displayed (no rules as display:none;)?
Where is your connection? If there isn't one, mysql_query() tries to make one by calling mysql_connect() with no args. It also fails if your connection doesn't have permissions for the table you're trying to read. If it's not dying but only returning no result, then check mysql_num_rows()
correct quotes of this line ::
$result1 = mysql_query("select * from suppliers where supp_short_code='WED'") or die(mysql_error());

Categories