MySQL Delete Item from Table not working - php

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.

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.

delete photo script gives errors in php and mysql

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";

Is using mysql_num_rows (rowCount in PDO) necessary in update or insert query?

Should I be using mysql_num_rows (rowCount in PDO) in update or insert query?
Currently, my code looks likes this,
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$message = "Updated successfully";
return $message;
}else{
return false;
}
}
Should I change it to like this?
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$num = $r->rowCount();
if($num == 1){
$message = "Updated successfully";
return $message;
}else{
$message = "An error occurred";
return $message;
}
}else{
return false;
}
}
Normally, query goes through without any error, so I shouldn't worry about it too much, but which one would be a better coding practice? Or do you suggest something else?
Thanks so much in advance!
Actually the two codes do something different.
The first one will print "Update success" if the query was successfully executed. But a query can be successfully executed also without affecting any row, i.e. you have a WHERE statamenet that does not match. The second code will not print "Update success" if no rows were affected.
Of course, if you're sure that your WHERE statement has to match, you can use both codes without any difference and using the second one could help you to spot any potential bug, i.e. it doesn't match and so something went wrong (probably the id was different from the one you expected).
Generally, to answer your question, mysql_num_rows is needed only if you want to know how many lines were affected. It's not mandatory at all to use it.
So, it depends on what you want. Both are good, but they are different.
If you are 100% sure the variables are created by you and not someone else you can do it like that, but you can minimize the code more:
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id'";
if($db->query($q)){
return "Updated successfully";
}
return false;
}
First, because a query is executed successfully, doesn't necessarily mean that anything has been updated. So if you need to distinct the difference between a queries validity or the update change, then yes, rowCount would be a good practice.
Second, a prepared statement would be more wise to use when assigning variables (SQL injection, etc).
public function update_username(){
$q = "UPDATE usertable SET username = :user_name WHERE id = :user_id LIMIT 1";
$r = $db->prepare($q);
$r->bindValue(':user_name', $user_name);
$r->bindValue(':user_id', $user_id);
if($r->execute()){
$message = "Updated successfully: updated ".$r->rowCount();
return $message;
}else{
return false;
}
}
To avoid code duplication, maybe you should consider avoiding writing the same execution code for a query, and move that to a method/function which does that all for you, e.g
public function validateStmt($r) {
// validate query
if($r->execute()) {
// check result set
if($r->rowCount() > 0) {
return $r;
}
else {
// if a result set IS expected, then you might consider to handle this as
// a warning or an error
}
}
else {
// query invalid
}
}
Depending on the situation, you will have to choose which part you should use. mysql_num_rows() is used to check how many rows have been affected from your query you have executed. So, it's up to you to decide whether it is really necessary to add the mysql_num_rows() function in to your code or not.

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

How to get url ID in PHP? (for mysql_query UPDATE)

I want to add an edit button for a script called spiral url, but the problem is that I can't get the URL id. This is what I've tried:
/** get url id **/
$id = isset($_GET['id']) ? $_GET['id'] : '';
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".$id."' LIMIT 1");
What am I doing wrong?
Also I emailed the author and his response:
"I recommend you post on Stackoverflow - https://stackoverflow.com/.
I would love to help you but I don't see what you are doing wrong. I'm still learning PHP as well."
You're wide open to SQL injection attacks.
You're supressing errors with the # operator. NEVER suppress errors
You're not checking the return value of mysql_query(), which returns a boolean FALSE on failure.
Scrap that code and use this:
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "UPDATE short_urls SET long_url = 'test' WHERE url_id=$id LIMIT 1";
$result = mysql_query($sql);
if ($result === FALSE) {
die("Mysql error: " . mysql_error() . $sql);
}
Note that I'm assuming that the id parameter is numeric. If it's not, then remove the intval() stuff.
Make sure the value of $_GET['id'] actually has a value. Your URL will look something like http://myurl.com/index.phtml?id=yourvalue. You can do this by doing a:
print "id=".$_GET['id'];
Also, whenever doing a query, please be sure to escape any and all variables that can be manipulated by the user. Without doing this, you're opening yourself up to SQL injection attacks.
mysql_real_escape_string - http://php.net/manual/en/function.mysql-real-escape-string.php
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".mysql_real_escape_string($id)."' LIMIT 1");
If the url is like this: domain.com/something.php?id=65
$_GET['id'] should be equal to 65
if there is no id there then when you try to access $_GET['id'] you will get an error.
Also try removing the # symbol (that suppresses PHP warning).
And you are waaaay open to bobby-tables
Also (side note), get a new developer who knows what they are doing ;-)
Have you checked the url
http://www.somewebsite.com?id=56&other_car=test
specifically for the "?" after the end of the url and also check all the parts are broken up by the ampersand.
failing that you can view all of your available get array variables by
print_r($_GET);

Categories