-1

Been trying to delete a row in mysql like this but its not working. It echoes "failed to delete".

I dont know what is wrong with the code. Any suggestions will be welcomed.

<?php
 error_reporting(0);
 include("db_config.php");

// array for JSON response
$response = array();
if( isset($_GET['id'] ) ) {

    $id=$_GET['id'];
    $data=$_GET['data'];
    $item=$_GET['item'];
    $time=$_GET['time'];

    $result = mysql_query("delete from myorder where id='$id' ");

    $row_count = mysql_affected_rows();

    if($row_count>0){
        $response["success"] = 1;
        $response["message"] = "Deleted Sucessfully.";
       }
    else{
        $response["success"] = 0;
        $response["message"] = "Failed To Delete";
     }
  // echoing JSON response
  echo json_encode($response);

 }
?>

My table structure:

CREATE TABLE `myorder` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `data` varchar(20) NOT NULL,
  `item` varchar(255) DEFAULT NULL,
  `time` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;

And my primary data is:

INSERT INTO `myorder` VALUES(23, '500MB', 'safaricom \nsteve\n0715611306', '11:32 PM 26 Aug, 2015 ');
INSERT INTO `myorder` VALUES(24, '4GB', 'safaricom \nsteve\n0715611306', '00:30 AM 27 Aug, 2015 ');
INSERT INTO `myorder` VALUES(25, '9\nGB', 'airtel \nsteve\n0715611306', '00:31 AM 27 Aug, 2015 ');
INSERT INTO `myorder` VALUES(26, '9\nGB', 'airtel \nsteve\n0715611306', '00:31 AM 27 Aug, 2015 ');
Steve Kamau
  • 2,755
  • 10
  • 42
  • 73

3 Answers3

4

You are encasing your $id field with single quotes meaning that the SQL engine will parse '$id' as a string literal, this is not what you want as you would like to use the dynamic id passed to the function. To do this you can append the ID to the query by doing:

"DELETE FROM myorder WHERE id = " . $id;

Whilst this may work, there is a serious risk for SQL injection from a malicious user, I understand you're new to PHP but the sooner you find out about these dangers the better.

For example, a user may set $id to ;DELETE FROM myorder which would terminate the first query and run the second query, deleting all records in your myorder table. Even worse than this a malicious attacker may attempt to guess common names used for tables in schemas such as users and run a query like

;SELECT * FROM users

This could expose sensitive information such as usernames and passwords and really put you in a position you don't want to be in...

To solve this, there are some really popular database wrappers, my favourite PDO. It allows you to safely bind values to a query before it executes, prepared values will default to strings so they won't be parsed as queries on the server, thus voiding you from this sort of attack.

I have wrote a simple Database wrapper class that you could use to handle all CRUD operations, it can be found here. You could then use it like:

// Require the DB class and create an instance
require('../path/to/file/Database.php');
$db = new Database();

// Create a query, use the :param_name syntax to bind values
$query = "DELETE FROM myorder WHERE id = :id";

// Create the associative array that has data binding for values
$data = Array(":id" => $id);

// Run the query and capture the result
$deleted = $db->delete($query, $data);

// Check the result
if($deleted > 0)
    // deleted successfully
else
    // handle errors here

The query will now bind and run safely without risk of SQL injection, if you need any further help please ask.

Halfpint
  • 3,967
  • 9
  • 50
  • 92
  • Very helpful piece.I will definately check up on SQL injection instances jus to beon the safe side. – Steve Kamau Aug 26 '15 at 23:15
  • Don't blow it out of proportion, `;SELECT * FROM user` won't work because `mysql_query` only allows you to run one query. – Barmar Aug 27 '15 at 11:33
1

Take the quotes out from around $id in your query and concatenate just in case.

$sql = "DELETE FROM myorder WHERE id = ".$id;

Edit: As comments mentioned, you should be cleaning your variables before using them in a query to prevent sql injection.

I would recommend to first stop using mysql_ since it is no longer supported and switch to either mysqli_ or PDO. Personally I prefer PDO.

Here is a link to a post all about SQL injection How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
DiddleDot
  • 745
  • 5
  • 16
0

As this is I assume a script that is run from an AJAX call you are not going to be able to debug it using simple echo statements so try this, and then look with the broswer debugger at what is being sent to the browser in the JSON.

It might also be useful to see what is in db_config.php

<?php
 error_reporting(0);
 include("db_config.php");

// array for JSON response
$response = array();
if( isset($_GET['id'] ) ) {

    $id=$_GET['id'];
    //$data=$_GET['data'];   // not tested for so dont use
    //$item=$_GET['item'];   // not tested for so dont use
    //$time=$_GET['time'];   // not tested for so dont use

    $sql = "delete from myorder where id=$id";
    $result = mysql_query($sql);

    // you shoud always be checking error status after this command.
    if ( ! $result ) {
        $response['mysql_query'] = $sql;
        $response['mysql_error'] = mysql_error();
        echo json_encode($response);
        exit;
    }

    $row_count = mysql_affected_rows();
    $response['affectedRows'] = mysql_affected_rows();

    if($row_count>0){
        $response["success"] = 1;
        $response["message"] = "Deleted Sucessfully.";
    } else {
        $response["success"] = 0;
        $response["message"] = "Failed To Delete";
    }
  // echoing JSON response
  echo json_encode($response);

 }
?>

Also as you are obviously just learning PHP and MYSQL please dont waste your time learning the mysql_ database extension, it is deprecated (soon to be removed completely) in PHP7 its has been removed. Instead use your time more fruitfully and learn either the mysqli_ or PDO extensions. See this post for help in deciding which you prefer.

Community
  • 1
  • 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Also i tried your code and my browser shows `{"mysql_query":"delete from myorder where id=","mysql_error":"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 '' at line 1"}` – Steve Kamau Aug 26 '15 at 23:04
  • Hhmmmmm thats not desperately helpful is it. But at least we know there is an error – RiggsFolly Aug 26 '15 at 23:06
  • 1
    Ahhh. `$id` has nothing in it see the sql `where id=` i.e. no id passed to the code. I guess this means you are passing some wierd character from th android – RiggsFolly Aug 26 '15 at 23:08
  • the weirder thing @RiggsFolly is that the isset is going through. It's set but we don't know "what" that is. OP may need to escape it. OP needs to be clearer as to what is what. and if using `MySQL_` to connect with (?) – Funk Forty Niner Aug 26 '15 at 23:11
  • @RiggsFolly I thought the id was in the code.Let me update my question. – Steve Kamau Aug 26 '15 at 23:14