tags:

views:

73

answers:

5

Hello,

How do i pass id to delete record in this code?

<form action="index.php">
        <?php
                     mysql_connect('localhost', 'root', '');
            mysql_select_db('user');
            $query = mysql_query("Select * from tbluser");
            echo "<center>";
            echo '<table style="border:solid 2px black;">';
            while(($row = mysql_fetch_array($query)) != NULL) {
                echo '<tr>';
                echo '<td>' . $row['UserName'] . '</td>';
                echo '<td>' . $row['Password'] . '</td>';
                echo '<td>' . $row['EmailAddress'] . '</td>';
                echo '<td>' . $row['Address'] . '</td>';
                echo '<td>' . $row['Address'] . '</td>';
                echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';
                echo '</tr>';
            }
            echo '</table>';
            echo "</center>";
        ?>
          </form>

The above code is in index.php and it is submitting it to itself.

+1  A: 

Use this to submit the id as a part of form.

<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>" />

or you can send values in URL to do the same thing

An example:

<a href="index.php?action=delete&id=<? echo $row['id']; ?>">Delete</a>

A full working sample

<?
    mysql_connect('localhost', 'root', '');
    mysql_select_db('user');
    switch($_GET['action']) { 
        case "delete":
            $query = "DELETE FROM tbluser WHERE id='".$_GET['id']."'"
            $result = mysql_query($query);
            break;
        //well other actions
    }

    $query = mysql_query("Select * from tbluser");
    echo "<center>";
    echo '<table style="border:solid 2px black;">';
    while(($row = mysql_fetch_array($query)) != NULL) {
        echo '<tr>';
        echo '<td>' . $row['UserName'] . '</td>';
        echo '<td>' . $row['Password'] . '</td>';
        echo '<td>' . $row['EmailAddress'] . '</td>';
        echo '<td>' . $row['Address'] . '</td>';
        echo '<td>' . $row['Address'] . '</td>';
        echo '<td><a href="thispage.php?action=delete&id='.$row['id'].'">Delete</a></td>';
        echo '</tr>';
    }
    echo '</table>';
    echo "</center>";
?>
Starx
Ok but how is it going to be available in `$_GET` or `$_POST`? When i press delete how will the id be available?
Ankit Rathod
-1 Assuming multiple rows, `id="id"` is a bad idea.
George Marian
@Nitesh `$_GET['id']` or `$_POST['id']` depending on the method
quantumSoup
@George There is clearly only one row
quantumSoup
@George Marian, he will already have multiple submit button anywayif he has multiple rows
Starx
@Aircule There is? `while(($row = mysql_fetch_array($query)) != NULL)` Clearly, this could result in multiple rows. BTW, the `!= NULL` is unnecessary.
George Marian
This isn't a question of what is submitted by the form. It's a question of the requirements for the `id` attribute. It's supposed to be unique in the page.
George Marian
@George I guess I missed that. In that case it doesn't make sense for him to use a submit button - at least not the way it's being used.
quantumSoup
@Aircule Ah yes, even I missed that issue. The entire form would be submitted. Which user id would be the appropriate one to delete?
George Marian
However, by the way the OP is asking this question, I think It would be better if he would just send the id to the page through URL
Starx
@starx However, based on the HTTP spec he should not. GET requests should never have a side effect. They should simply return a representation of some resource identified by the URI
George Marian
@Geoge Marian, I agree but in this case I would definitely do that hehe.
Starx
@starx See, that's the problem. Why would you definitely do that in this case? Because you don't give enough priority to the specification? If it's because you don't know any better, that's forgivable. Assuming that you're willing to learn and improve your techniques. The whole RESTful webservices movement is based on the the idea of actually following the spec.
George Marian
@George, I would definitely love to learn about specs. Care to suggest me some resources, as you know quite a lot about this.
Starx
@Starx This is a good introduction to the ideas: http://quandyfactory.com/blog/65/designing_a_restful_web_application I don't have any other links handy, but you can search for things like `HTTP specification` or`RESTful web servcies` If I think of more, or dig up some decent links I'll reply here. This wikipedia article looks decent, as well: http://en.wikipedia.org/wiki/Representational_State_Transfer
George Marian
Sure man.............
Starx
A: 

From the table:

echo '<input type="hidden" name="user_id" value="'.$row['id'].'" />';
echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';

This will be sent to the server as a parameter named user_id. Ideally, you should be using the POST method in the form.

This assumes that the user id is named, well id in the table.

BTW, the != NULL is unnecessary.

It's sufficient to write:

while($row = mysql_fetch_array($query)) {

NULL evaluates to FALSE in a boolean context.

Update:

As mentioned in comments to another answer, there is an issue with your approach. With multiple rows, you won't be able to distinguish between user ids.

One solution would be use multiple forms.

Another option would be to have the name of the submit button include the id. You'd then parse this out of the name of the $_POST array keys.

George Marian
Sorry but it is not working. When i `var_dump($_POST)` i always get `array(2) { ["id"]=> string(1) "3" ["btnDel"]=> string(6) "Delete" } `, no matter whichever button i click. Can you help me please?
Ankit Rathod
@George, Why are you including @Ryan's answer to yours?
Starx
@Starx That was a coincidence. I had the edit window open while thinking it through. (I'm on only 3 hours of sleep. One of the reasons that my answer is light on code, and why I missed the unnecessary comparison in the while condition, and the original issue w/ using one form.)
George Marian
A: 

You could also send it in the url at action="index.php" given that you move it below while(($row = mysql_fetch_array($query)) != NULL) { like this

echo "<form action='index.php?var=" . $row['id'] . "'>";

You would then get the variable using $_GET['var']

If the id needs to stay hidden (on the page and in the link) a hidden input element and submitting the form using method="post" like previously suggested would be the better way to go.

Ryan
@Ryan, the case is of multiple rows here, one particular id is not going to be very useful I think
Starx
GET requests should never have a side effect. They should simply return a representation of some resource identified by the URI. (gah, typos)
George Marian
@Starx, thats why I suggested the form itself be moved into the while, that would create a form for each row returned (with it's unique ID in the action URL). Your method above is a better way to do what I was trying to get across, though. @George Marian, don't know what you mean, do you just have a problem with hard-coding variables into URL's?
Ryan
Well Ryan, there is nothing wrong with your method, except its a very vague solution and little bit inefficient, but yours and mine would work perfectly in case of disabled Javascript. and @George how ever is just talking about best practices and HTTP specs.
Starx
@Ryan I just noticed your question. Basically, GET requests shouldn't cause anything to change on the server. That's what I'm getting at. Now, if we want to get really technical, it's the DELETE method that should be used for this operation. But, I don't want to open that can of worms right now.
George Marian
+2  A: 

Here's how I would do it:

Change

echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';

To

echo '<td><input type = "button" value = "Delete" onclick = "btnDel(' . $row['id'] . ')" /></td>';

Add the following field to the form (outside of the while loop of course):

<input type="hidden" name="id" id="userid" />

Define the following javascript function:

function btnDel(id) {
    if (confirm("Really delete id=" + id + "?")) {
        document.getElementById('userid').value = id;
        document.forms[0].submit();
    }
}​

Then you can retrieve that value using $_GET['id'] or $_POST['id'] depending on your form's method.


EDIT: Here's a working demo, and its source

quantumSoup
However, we should not rely on JavaScript being enabled. Especially, when there are ways to do it without JavaScript.
George Marian
Besides, this questions was tagged PHP and mysql only, I dont think OP was expecting a javascript solutions but as he accepted it, I guess he did. Funny though.....
Starx
I accepted because i tried George Marian's solution but it didn't work. This looked promising to me and infact it did work.
Ankit Rathod
@starx Give a man a fish and he'll keep coming back for more fish. Unfortunately, not everyone is interested in learning. Many just want an easy fix.
George Marian
@Nitesh Look at my update. You can wrap each record in it's own form. I would put that form, in it's entirety, in one table element.
George Marian
@Nitesh Demo added. Be careful to make sure to have a way for users who have JS disabled to do this.
quantumSoup
+5  A: 

Without needing javascript, seperate GET urls etc, just plain old HTML & the original POST: just add the ID to the name of the button:

<input type="submit" value="Delete" name="btnDel[<?php echo $id;?>]">

And in receiving code:

if(isset($_POST['btnDel']) && is_array($_POST['btnDel'])){
    foreach($_POST['btnDel'] as $id_to_delete => $useless_value){
        //delete item with $id_to_delete
    }
}
Wrikken
Exactly what i wanted. Without query strings and without javascript :)
Ankit Rathod
+1 I like this.
quantumSoup
+1 despite feeding him :)
George Marian
+1, Cool Answer
Starx
@George Marian: ah, I only know see this solution was indeed in the last sentence in your answer. But let's be honest: feeding me? According to the timestamp staring at me right know, your edit was 23 mins ago, my answer 32 mins ago. A question of 'who was feeding who', or 'great minds think alike', take your pick :)
Wrikken
@Wrikken I think he meant feeding the OP
quantumSoup
@Wrikken Yes, I was referring to the OP. Being an educator at heart, I tend to prefer giving them enough to figure it out. That said, the comment was a bit hasty.
George Marian
@George Ah, a misunderstanding on my part, my apologies :) Not being a native English speaker I tend to let the code do a lot of talking for me, which can be considered feeding indeed.
Wrikken
@Wrikken No worries. I totally see why you drew that conclusion. Completely understandable. As far as the feeding comment, that's debatable. It's not like you took his code and did it all for him. So, my apologies for that.
George Marian