www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: Delete from sql database with javascript/php

  1. #1
    Join Date
    Jul 2009
    Posts
    13

    Delete from sql database with javascript/php

    Hi! I have made a page which shows customers order info, trackingnr and so on. What I want is to be able to delete orders. I have already made a delete button but im unsure of the javascript code to remove ordres. I have the following code
    Code:
    <?php
    
    class status {
    
        function status() {
        }
        
        
        function displayStatus() {    
            global $mysql;
            
            $user_id = $_SESSION['user_id'];
              $result = $mysql->query("SELECT ordrer.kunde_id, ordrer.status, ordrer.sporingsnummer, ordrer.dato, ordre_detaljer.id, ordre_detaljer.ordre_id, ordre_detaljer.varenavn FROM ordrer, ordre_detaljer WHERE ordrer.kunde_id='{$user_id}' and ordrer.ordre_id=ordre_detaljer.ordre_id limit 10");
            
        
              echo "<br />
              <br />
              <table width=\"800\" align=\"center\" style=\"font-size:13px;\">
              <tr style=\"font-size:;\">
                  <td width=\"90\" align=\"center\"><b>Ordrenr</b></td> 
                <td width=\"120\" align=\"center\"><b>Ordrestatus</b></td>
                <td width=\"150\" align=\"center\"><b>Sporingsnummer</b></td>
                <td width=\"200\" align=\"center\"><b>Beskrivelse</b></td>
                <td width=\"100\" align=\"center\"><b>Dato</b></td>
                
                
            </tr>";
          
             while($row = mysql_fetch_array($result)) {
                  echo "
                  <tr>
                      <td align=\"center\">".$row["ordre_id"]."</td>
                      <td align=\"center\">".$row["status"]."</td>
                      <td align=\"center\">".$row["sporingsnummer"]."</td>
                      <td align=\"center\">".$row["varenavn"]."</td>
                      <td align=\"center\" style=\"font-size:12px;\">".$row["dato"]."</td>
                    <td align=\"center\"><button type=\"button\" onclick=\"delete()\">Delete</button></td>
                  </tr>";
            }
            echo "</table>";
            
        
          
        }
    
    }
          
    ?>
    and

    delete.php

    Code:
    <?php
    global mysql;
    var $ordre_id = $_GET["oid"];
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$ordre_id}'");
    $mysql->query("DELETE FROM ordre_detaljer WHERE ordre_id='{$ordre_id}'");
    
    echo 'OK';
    ?>

  2. #2
    Join Date
    Aug 2009
    Posts
    13
    You could do one of two things.

    If you want to delete without reloading the page, then i would recommend that you get a javascript library with ajax capabilities, like jQuery

    It will make your life alot easier, especially with big projects like a webshop.

    (you could of course do it without a library, but you will need to spend some time getting familar with ajax)

    Then you need to make a post to delete.php, with the order id, and a token for security check.

    With jQuery, it would look like
    Code:
    function delete(order_id, token) {
    
    
    $.ajax({
    url: 'delete.php', cache: false, data: 'order_id=' + order_id + '&token=' + token, type: 'POST', success: function(response){
    alert('order deleted');
    }
    });
    }
    If you want to do it without javascript (which would be alot easier) you simply make a link pointing to the page you are on, with a delete=order_id value
    Code:
    <a href='/yourpage/?delete={$order_id}'>Delete</a>
    And then in the top of your page
    Code:
    if (isset($_REQUEST['delete'])) {
    
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['order_id']}'");
    }
    Of course you need some security check, but i figure that this is for the admin part of a site?

    Btw, it's bad practice to mix danish and english in your code :-)
    It would help you alot in the long run to stick to english, and only use danish when it's something users need to read.
    Especially when you need support on a forum ;-)

    Hope this helps, let me know if you need further explanations.

    /Benjamin

  3. #3
    Join Date
    Jul 2009
    Posts
    13
    Thx for your reply Benjamin. Its actually norwegian . I was thinking of translating before i posted but it was so much .. I tried ur second suggestion (easy way). I am unsure if the if sentence is where it should be, u suggested top of the page. When i try the code i get " www.myshop.no/status/?delete= " in the URL and 404 error. Seems like it doesnt get the order id?

    Here is the code now:


    Code:
    <?php
    
    	if (isset($_REQUEST['delete'])) {$mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['order_id']}'");
    }
    class status {
    
    	function status() {
    	}
    
    	
    	function displayStatus() {	
    		global $mysql;
    		
    		$user_id = $_SESSION['user_id'];
    	  	$result = $mysql->query("SELECT ordrer.kunde_id, ordrer.status, ordrer.sporingsnummer, ordrer.dato, ordre_detaljer.id, ordre_detaljer.ordre_id, ordre_detaljer.varenavn FROM ordrer, ordre_detaljer WHERE ordrer.kunde_id='{$user_id}' and ordrer.ordre_id=ordre_detaljer.ordre_id limit 10");
    		
    	  	
    	  	echo "<br />
    	  	<br />
    	  	<table width=\"800\" align=\"center\" style=\"font-size:13px;\">
    	  	<tr style=\"font-size:;\">
      			<td width=\"90\" align=\"center\"><b>Ordrenr</b></td>
    	    	<td width=\"120\" align=\"center\"><b>Ordrestatus</b></td>
            	<td width=\"150\" align=\"center\"><b>Sporingsnummer</b></td>
            	<td width=\"200\" align=\"center\"><b>Beskrivelse</b></td>
            	<td width=\"100\" align=\"center\"><b>Dato</b></td>
    			
    			
            </tr>";
    	  
    	 	while($row = mysql_fetch_array($result)) {
    		  	echo "
    		  	<tr>
    		  		<td align=\"center\">".$row["ordre_id"]."</td>
    		  		<td align=\"center\">".$row["status"]."</td>
    		  		<td align=\"center\">".$row["sporingsnummer"]."</td>
    		  		<td align=\"center\">".$row["varenavn"]."</td>
    		  		<td align=\"center\" style=\"font-size:12px;\">".$row["dato"]."</td>
    				<td align=\"center\"><a href='/status/?delete={$order_id}'>Delete</a></td>
    		  	</tr>";
    		}
    		echo "</table>";
    		
    	
    	  
    	}
    
    }
    	  
    ?>

  4. #4
    Join Date
    Jul 2009
    Posts
    13
    I changed the bottom code to
    Code:
    <td align=\"center\"><a href='/status/?delete={$row["ordre_id"]}'>Delete</a></td>
    But i still get "www.myshop.no/status/?delete=2042" 404 not found. So it gets the right order nr but still doesnt work.. ?

  5. #5
    Join Date
    Aug 2009
    Posts
    13
    Do you have rewrite-engine turned on?

    If not, you will have to call status.php?delete=xxxx, instead of /status/?delete=xxxx

    Remember that validation of the $_REQUEST parameter is CRUCIAL when you are doing database actions

    Code:
    if (isset($_REQUEST['delete'])) {
    
    if (!eregi("[0-9]{4}", $_REQUEST['delete']) {
    die('Invalid ID');
    } else {
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['order_id']}'");
    }
    }

    Edit: Ahh, i think i found the error.

    Replace
    Code:
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['order_id']}'");
    with
    Code:
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete']}'");
    $_REQUEST['order_id'] was never set in the first place.
    Either call it $_REQUEST['order_id'] or $_REQUEST['order_delete']
    Last edited by b3nj4m1n; 08-03-2009 at 12:11 PM.

  6. #6
    Join Date
    Jul 2009
    Posts
    13
    Some other guy coded most of this page. When i am on status.php it says www.myshop.no/index.php?menu=status . So i am unsure of the url i have to type in href.

    I also tried
    Code:
    <td align=\"center\"><a href='/index.php?delete={$row["ordre_id"]}'>Delete</a>
    Then i got " Fatal error: Call to a member function query() on a non-object in /home/elitetgd/public_html/php/status.php on line 5"

  7. #7
    Join Date
    Aug 2009
    Posts
    13
    You probably need it to be
    Code:
    <a href='/index.php?menu=status&delete={$row["ordre_id"]}'>Delete</a>
    You should set a standard value for menu in the top of your page, so it will always be set (doesnt REALLY matter if its in the admin menu, but good practice anyways)

    Top:
    Code:
    $menu = 'standard';
    
    if (isset($_REQUEST['menu'])) {
    
    if ($_REQUEST['menu'] == "something") $menu = "something"; if ($_REQUEST['menu'] == "somethingelse") $menu = "somethingelse";
    } include_once "{$menu}.php";
    ...or something like that

  8. #8
    Join Date
    Jul 2009
    Posts
    13
    I tried
    Code:
    <a href='/index.php?menu=status&delete={$row["ordre_id"]}'>Delete</a>
    I press delete then i get:

    URL = http://www.myshop.no/index.php?menu=status&delete=2042


    "Fatal error: Call to a member function query() on a non-object in /home/elitetgd/public_html/php/status.php on line 5"


    So url and orderid is correct but something wrong with sql ?

  9. #9
    Join Date
    Aug 2009
    Posts
    13
    You could also consider doing something like this, if you have a lot of parameters in the URL
    Code:
    $query_str ="";
    
    $count = count($_GET);
    $i = 1;
    
    foreach ($_GET AS $var => $val) {
    	
    
    $query_str .="{$var}={$val}"; if ($i != $count) $query_str .= "&"; $i++;
    }
    And then just add extra parameters as needed, like
    Code:
    <a href='/index.php?{$query_str}&delete={$row['ordre_id']}'>Delete</a>
    Last edited by b3nj4m1n; 08-03-2009 at 01:14 PM.

  10. #10
    Join Date
    Jul 2009
    Posts
    13
    It works now with
    [CODE]function deleteOrder() {
    global $mysql;
    $user_id = $_SESSION['user_id'];
    if (isset($_REQUEST['delete'])) {

    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete]}'");
    $mysql->query("DELETE FROM ordre_detaljer WHERE ordre_id='{$_REQUEST['delete']}'");

    }}[/CODE
    Last edited by Kanie12; 08-03-2009 at 01:23 PM.

  11. #11
    Join Date
    Aug 2009
    Posts
    13
    No, it's the SQL statement, or the way you call the databse that is screwing around.
    The last post was just a good thing to do under any circumstance :-)

    Can you post the whole page? Or send me a pm with your gmail, skype or msn account, then i'll have a look!

  12. #12
    Join Date
    Jul 2009
    Posts
    13
    It works now with
    [code]function deleteOrder() {
    global $mysql;
    $user_id = $_SESSION['user_id'];
    if (isset($_REQUEST['delete'])) {

    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete]}'");
    $mysql->query("DELETE FROM ordre_detaljer WHERE ordre_id='{$_REQUEST['delete']}'");

    }}[/CODE

    THX ALOT!

    I would like to use
    if (isset($_REQUEST['delete'])) {
    if (!eregi("[0-9]{4}", $_REQUEST['delete']) {die('Invalid ID');} else {$mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete']}'");}
    but there seems to be a typo or something :P

  13. #13
    Join Date
    Aug 2009
    Posts
    13
    Code:
    if (isset($_REQUEST['delete'])) {
    
    if (!eregi("[0-9]{4}", $_REQUEST['delete'])) {
    die('Invalid ID');
    } else {
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete']}'");
    }
    }
    ...should do it :-)

    Remember that the regular expression needs to be modified.

    [0-9] means that it has to be characters between 0 and 9, and {4} means that it has to be precisely 4 characters long.
    So if you plan on having e.x between 4 and 6 characters, you could say "[0-9]{4,6}"

    You should read a bit about regular expressions, it is very important for security to double check every value coming from the outisde of your script.
    Especially with a web shop.

  14. #14
    Join Date
    Jul 2009
    Posts
    13
    That worked perfectly .. But now anyone can delete an order if the order exists and just change number in url "http://www.myshop.no/index.php?menu=status&delete=2266" . So i was thinking i need to increase security by checking if an order belongs to that user which is logged in. For that i need to first fetch all orders from the user and the compare somehow right ? I already have code for fetching orders

    Code:
    $result = $mysql->query("SELECT ordrer.kunde_id, ordrer.status, ordrer.sporingsnummer, ordrer.dato, ordre_detaljer.id, ordre_detaljer.ordre_id, ordre_detaljer.varenavn FROM ordrer, ordre_detaljer WHERE ordrer.kunde_id='{$user_id}' and ordrer.ordre_id=ordre_detaljer.ordre_id limit 10");

  15. #15
    Join Date
    Aug 2009
    Posts
    13
    This should help:

    Code:
    if (isset($_SESSION['user']['id'])) {
    
    if (isset($_REQUEST['delete'])) {
    if (!eregi("[0-9]{4}", $_REQUEST['delete'])) {
    die('Invalid ID');
    } else {
    $order = $mysql->query("SELECT user_id FROM ordrer WHERE ordre_id='{$_REQUEST['delete']}'"); if (isset($order['ordre_id']) && $order['ordre_id'] == $_SESSION['user_id']) {
    $mysql->query("DELETE FROM ordrer WHERE ordre_id='{$_REQUEST['delete']}'");
    }
    }
    }
    }
    And then of course something like this
    Code:
    <td align=\"center\">
    
    ".(isset($_SESSION['user_id']) && $_SESSION['user_id'] == $row['user_id'] ? "<a href='/index.php?menu=status&delete={$row['ordre_id']}'>Delete</a>" : "&nbsp;")."
    </td>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles