Jump to content

[SOLVED] Help With editting and deleting form


netpumber

Recommended Posts

Hallo !!

 

So look at this image :

 

http://img194.imageshack.us/img194/8272/snapshot5f.png

This table prints the titles of entries from a table in a database.. The code that i use for this table is this :

<!--Table For Deleting and Updating -->

<br>
<br>
<p align="center"><font color="#1569C7">DeleteOrEdit(</font><font color="red">Security Projects & Thoughts Section</font><font color="#1569C7">);</font></p>

<table align="center" border="2" bordercolor="green" cellspacing="0">

<!--First row with title delete and edit-->
<tr>
<td><font color="#F87217">Title:</td>
<td><font color="#F87217">Delete();</font></td>
<td><font color="#F87217">Edit();</font></td>
</tr>

<?php

$query = 'SELECT title FROM site_entries ORDER BY date_entered DESC';

if ($r = mysql_query($query)){

        while ($row = mysql_fetch_array($r)){
                  print "<tr>
                         <td><font color=\"#8BB381\">{$row['title']}</td>
                         <td><form method=\"post\"  name=\"sub_del\"><input  type=\"submit\" value=\"Delete();\"></form></td>
                         <td><form method=\"post\" name=\"sub_edt\"><input type=\"submit\" value=\"Edit();\"></form></td>
                         </tr> ";

                                             }
}else{
        die('<p>Could not retrive the data brcause:<b>' . mysql_error .'</b> The query was $query.</p>');

}


mysql_close();


?>

</table>

 

Its simple...till here...

 

Now i stack on how to make the script that will delete the registers of the database...I can think something with id column but i can't make it true...:s I want you to help me giving me ideas on how to make this or any other idea on how to create an delete/edit page...If you think that i start it with a wrong way please tell me :)

 

The table name is site_entries and its columns are id , title , entry , date_entered

 

Thanks in advance..!!

 

 

Link to comment
Share on other sites

how about this...

 

place your <form> tags outside of the table.

 

then, edit your PHP code to output the following for each row:

<tr>
<td><font color="#8BB381">{$row['title']}</td>
<td><input  type="submit" name="{$row['id']}" value="Delete"></td>
<td><input  type="submit" name="{$row['id']}" value="Edit">
</tr>

 

in your form-processing page, simply pick out the id and value from the $_POST field (there should only be one element in the array, print_r($_POST) if you are unsure how to handle it).

 

Might not be the most efficient way, but it should be the fastest and easiest to code.

 

HTH

 

 

Edit: Remember to change your MySQL query to SELECT the id too!

Link to comment
Share on other sites

hmm...Seanlim... i do what you said an here is the new code:

 

<form method="post" action="edmp.php">
<table align="center" border="2" bordercolor="green" cellspacing="0">
                         <tr>
                         <td><font color="#F87217">Title:</td>
                         <td><font color="#F87217">Delete();</font></td>
                         <td><font color="#F87217">Edit();</font></td>
                         </tr>


<?php

$query = 'SELECT title,id FROM site_entries ORDER BY date_entered DESC';

if ($r = mysql_query($query)){

        while ($row = mysql_fetch_array($r)){
                  print "
                         <tr>
                         <td><font color=\"#8BB381\">{$row['title']}</td>
                         <td><input  type=\"submit\" name=\"{$row['id']}\" value=\"Delete();\"></td>
                         <td><input type=\"submit\" name=\"{$row['id']}\" value=\"Edit();\"></td>
                         </tr> ";

                                             }
}else{
        die('<p>Could not retrive the data brcause:<b>' . mysql_error .'</b> The query was $query.</p>');

}


?>

</table>
</form>


<?php
//Deleting a register

if (isset($_POST['submit'])){

        $query = "DELETE FROM site_entries WHERE id={$row['id']} LIMIT 1";
        $r = mysql_query($query);
}
mysql_close();
?>

 

the prob is that when i press the delete button nothing happens...

 

Maybe something is going wrong with the {$row['id']} but i dont know...What you say?

Link to comment
Share on other sites

heh.. you can't test for $_POST['submit'], cos it isn't called submit anymore!

 

when the user clicks on delete, the $_POST variable will have an element something like $_POST['2'] = "Delete" if the row id is 2.

 

As said in my previous post, use print_r($_POST) to get an idea of how to read the posted variables.

 

I would also suggest that your form submit the data to another PHP page, or at least the same page with a $_GET variable. This way, the script can easily know if Delete/Edit was clicked.

 

<form method="post" action="{$_SERVER['PHP_SELF']}?submit">
...
<?php
if(isset($_GET['submit'])){
$a = array_keys($_POST);

$id = $a[0];
$action = $_POST[$id];

if($action=="Delete"){
...
}
}
?>

Link to comment
Share on other sites

First i want to test it with post method.. Anyway.. i change as you say the php script to another file . delete.php

 

and there i add print_r($_POST); line...

 

I get this:

Array ( [23] => Delete(); )

 

It takes the id=23 as we can see...and the button's value = Delete();

 

How i can make it work with DELETE query ? I ll try it later with $_GET but im curious now on how it works with POST. Here is the code once again with some changes:

 

delete.php

 

<?php
//[start] of DeleteOrEdit section

ini_set('display_errors',1);
error_reporting(E_ALL);

        if ($dbc = @mysql_connect('localhost','we','p@ss'))
                {
                        if (!@mysql_select_db ('web_site'))
                        {
                                die('<p> Could not select the database brcause:<b>'. mysql_error() .'</b></p>');
                        }
                }else{
                        die('<p>Could not connect to MYSQL because:<b>' . mysql_error() . '</b></p>');
                        }



//Deleting a register

if (isset($_POST['submit'])){

        $query = "DELETE FROM site_entries WHERE id={$row['id']} LIMIT 1";
        $r = mysql_query($query);
}
print_r($_POST);
mysql_close();
?>

 

edmp.php

 

<form method="post" action="delete.php">
<table align="center" border="2" bordercolor="green" cellspacing="0">
                         <tr>
                         <td><font color="#F87217">Title:</td>
                         <td><font color="#F87217">Delete();</font></td>
                         <td><font color="#F87217">Edit();</font></td>
                         </tr>


<?php

$query = 'SELECT title,id FROM site_entries ORDER BY date_entered DESC';

if ($r = mysql_query($query)){

        while ($row = mysql_fetch_array($r)){
                  print "
                         <tr>
                         <td><font color=\"#8BB381\">{$row['title']}</td>
                         <td><input  type=\"submit\" name=\"{$row['id']}\" value=\"Delete();\"></td>
                         <td><input type=\"submit\" name=\"{$row['id']}\" value=\"Edit();\"></td>
                         </tr> ";

                                             }
}else{
        die('<p>Could not retrive the data brcause:<b>' . mysql_error .'</b> The query was $query.</p>');

}

mysql_close();

?>

</table>
</form>

Link to comment
Share on other sites

You didn't get my point.. read this carefully: you can't test for $_POST['submit']. Your condition (isset($_POST['submit'])) will always be false because there is no form element called submit.

 

Therefore, you cannot use the usual method of testing whether the array element "submit" exists. You have 3 easy work arounds here:

 

1) Count the number of elements in the $_POST array. Check if there is 1 element.

2) Post the form to the same page with a $_GET variable (i.e. $_SERVER['PHP_SELF']."?submit"). Check that the $_GET variable exists

3) Post the form to another php page.

 

I was suggesting method number 2 or 3 in my previous post. I would also suggest that you continue using method="post" for your form.

 

Your MySQL query to delete the record seems well-formed. The script should therefore work once you get the above-mentioned condition right.

Link to comment
Share on other sites

Admittedly, my method of solving this isn't exactly orthodox. The name of the "submit" button isn't usually used to store a value. However, this is the easiest and shortest method I can think of to solve your problem

 

These are 2... more-orthodox solutions:

 

A Form for Each Record

This is similar to your initial attempt, but instead of a form for each button, creating one for each record is sufficient. The form will contain the two buttons: "Delete()" and "Edit()". A third element, a hidden input field will store the id of the record

 

Javascript and onclick Event

The other, less preferred, method is to use the onclick Javascript event. To use this method, you need only one form around your entire table, and a hidden input field. On each button, use the onclick event to update the hidden field (replace form_name with your form name):

 

<input type="submit" name="submit" value="Delete()" onclick="this.form_name.id.value='{$row['id']}'">
<input type="submit" name="submit" value="Edit()" onclick="this.form_name.id.value='{$row['id']}'">

 

 

 

For both of these methods, the following should be used to create the hidden field:

 

<input type="hidden" name="id" value="{$row['id']}">

 

Also, in both of these methods, your PHP script must check if the $_POST['submit'] variable exists. If it does, get the value of the variable to determine the action required (delete or edit). $_POST['id'] will then hold the id of the record which needs editing/deleting.

 

The first method is highly recommended even though it is heavy on HTML code. The second requires Javascript to work and is therefore unreliable.

 

Hopefully this is comprehensive enough for you to tackle the problem.

 

 

EDIT: It just hit me, you don't seem to *need* a form. But at least the above satisfies your curiosity :P The BEST method to do this is to use

<a href="{$_SERVER['PHP_SELF']}?action=delete&id={$row['id']}">Delete()</a>
<a href="{$_SERVER['PHP_SELF']}?action=edit&id={$row['id']}">Edit()</a>

and test for $_GET['action']. No forms, clean and simple.

Link to comment
Share on other sites

Thank you a lot seanlim :) for your answers...

 

So after 6 tries with $_POST  i decide to make it with the last way you say...:) Here is my code now:

 

<?php

$query = 'SELECT title,id FROM site_entries ORDER BY date_entered DESC';

if ($r = mysql_query($query)){

        while ($row = mysql_fetch_array($r)){
                  print "
                         <tr>
                         <td><font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#8BB381\">{$row['title']}</td>
                         <td><a href=\"{$_SERVER['PHP_SELF']}?action=delete&id={$row['id']}\">Delete();</a></td>
                         <td><a href=\"{$_SERVER['PHP_SELF']}?action=edit&id={$row['id']}\">Edit();</a></td>
                         </tr> ";

                                             }
}else{
        die('<p>Could not retrive the data brcause:<b>' . mysql_error .'</b> The query was $query.</p>');

}


if ($_GET['action'] == "delete"){
        $query = "DELETE FROM site_entries WHERE id={$row['id']} LIMIT 1";
        $r = mysql_query($query);
}

mysql_close();

?>

 

It returns me this error

 

Notice: Undefined index: action in /var/www/login/edmp.php on line 259

 

and i thing that i have an error in the checking $_GET['action'] part...in the if clause..What do you think ?

 

Also i have another question...Ok.. with delete link its just execute a DELETE query...what happens with the edit ? Maybe this one needs a POST method i think..cuz it needs a form with the new title and text ...Thats my opinion..Except if we can make it to redirects you to a new edit page...

 

Thanks for all!! I really mean it.. :) You help me to learn lot of things .

Link to comment
Share on other sites

Yes, you need to check if $_GET['action'] exists:

 

if(isset($_GET['action']) && $_GET['action']=="delete"){
...

 

After you have determined that $_GET['action']=="edit", your script should output a form which allows the user to submit the changes.

Link to comment
Share on other sites

Still doesnt work...

 

<table align="center" border="2" bordercolor="green" cellspacing="0"><?php

$query = 'SELECT title,id FROM site_entries ORDER BY date_entered DESC';

if ($r = mysql_query($query)){

        while ($row = mysql_fetch_array($r)){
                  print "
                         <tr>
                         <td><font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#8BB381\">{$row['title']}</td>
                         <td><a href=\"{$_SERVER['PHP_SELF']}?action=delete&id={$row['id']}\">Delete();</a></td>
                         <td><a href=\"{$_SERVER['PHP_SELF']}?action=edit&id={$row['id']}\">Edit();</a></td>
                         </tr> ";

                                             }
}else{
        die('<p>Could not retrive the data brcause:<b>' . mysql_error .'</b> The query was $query.</p>');

}


if(isset($_GET['action']) && $_GET['action']=="delete"){
        $query = "DELETE FROM site_entries WHERE id={$row['id']} LIMIT 1";
        $r = mysql_query($query);
}

mysql_close();

?></table>

Link to comment
Share on other sites

Hmm see here i add some code for errors and i get this one back:

Could not delete the entry because: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 'LIMIT 1' at line 1. The query was DELETE FROM site_entries WHERE id= LIMIT 1.

 

Link to comment
Share on other sites

and its still not working? the script looks fine... what is the MySQL error that you get now?

 

as a side note, i think this is safer:

 

$query = "DELETE FROM site_entries WHERE id='".mysql_real_escape_string($_GET['id'])."' LIMIT 1";

 

Link to comment
Share on other sites

Hmmm I need your help once again...

 

i add this for the edit link

 

<?php


if(isset($_GET['action']) && $_GET['action']=="edit"){

        print "<br><table align=\"center\"><td>
<form method=\"post\" name=\"misc\" action=\"edmp.php\" >
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\" >\$title :</font>
<br>
<input style=\"background:#B0D2D7\" type=\"text\" name=\"title\" size=\"38\" value={$row['title']}>
<br><br>
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\">\$text:</font>
<br>
<textarea style=\"background:#B0D2D7\" rows=\"10\" name=\"entry\" cols=\"48\" ></textarea>
<br>
<p align=\"center\"><INPUT type=\"submit\" name=\"submit1\" value=\"Submit\"></p>
</form>
</td></table>";
}
?>

 

I want to ask you how in the text and in the textarea i will load the title and the entry text from the database with the specific id number...

 

Any ideas...:)

 

Thanks...

Link to comment
Share on other sites

Use a MySQL query to retrieve the needed information:

 

$q = mysql_query("SELECT title,entries FROM site_entries WHERE id='".mysql_real_escape_string($_GET['id'])."'")
$row = mysql_fetch_array($q);
?>
...
//$row['title'] will now hold your title
<input type="text" name="title" value="<?=$row['title']?>">
...
<textarea name="entry"><?=$row['entries']?></textarea>

 

Link to comment
Share on other sites

Ok i have this :

 

<?php


if(isset($_GET['action']) && $_GET['action']=="edit"){
        $q = mysql_query("SELECT title,entry FROM site_entries WHERE id='".mysql_real_escape_string($_GET['id'])."'");
        $row = mysql_fetch_array($q);

print "
<br>
<table align=\"center\"><td>
<form method=\"post\" name=\"misc\" action=\"edmp.php\" >
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\" >\$title :</font>
<br>
<input style=\"background:#B0D2D7\" type=\"text\" name=\"title\" size=\"38\" value=\"{$row['title']}\">
<br><br>
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\">\$text:</font>
<br>
<textarea style=\"background:#B0D2D7\" rows=\"10\" name=\"entry\" cols=\"48\" ></textarea>
<br>
<p align=\"center\"><INPUT type=\"submit\" name=\"submit1\" value=\"Submit\"></p>
</form>
</td>
</table>
";
}
?>

 

But when it prints the form the Title is out of the text box :P lol and its near it..

 

Something is not good in this line.. I change it a little bit but... i didnt found anything..

<input style=\"background:#B0D2D7\" type=\"text\" name=\"title\" size=\"38\" value=\"{$row['title']}\">

Link to comment
Share on other sites

You mean the $row['title'] actually holds html tags? if so, you will have to use htmlentities to escape the output:

 

print "...
<input style=\"background:#B0D2D7\" type=\"text\" name=\"title\" size=\"38\" value=\"".htmlentities($row['title'])."\">
...";

Link to comment
Share on other sites

So look at this.

 

i have this code for editing the registers :

 

<?php


if(isset($_GET['action1']) && $_GET['action1']=="edit"){
        $q = mysql_query("SELECT title,entry FROM misc_entries WHERE id='".mysql_real_escape_string($_GET['id'])."'");
        $row = mysql_fetch_array($q);


print "
<br>
<table align=\"center\"><td>
<form method=\"post\" name=\"edit_misc\" action=\"editm.php\" >
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\" >\$title :</font>
<br>
<input style=\"background:#B0D2D7\" type=\"text\" name=\"title\" size=\"38\" value=\"".htmlentities($row['title'])."\">
<br><br>
<font face=\"Lucida Console, Courier New, Fixed\" size=2 color=\"#FFF380\">\$text:</font>
<br>
<textarea style=\"background:#B0D2D7\" rows=\"10\" name=\"entry\" cols=\"48\" >{$row['entry']}</textarea>
<br>
<p align=\"left\"><INPUT type=\"submit\" name=\"edit_misc\" value=\"Save\"></p>
<input type=\"hidden\" name=\"id\" value=\"".$_GET['id']."\">
</form>
</td>
</table>
";
}
?>

 

The code in editm.php script is :

 

<?php
// [start] Save changes for misc
ini_set ('display_errors',1);
error_reporting (E_ALL);

if (isset ($_POST['edit_misc'])){
        if ($dbc = @mysql_connect('localhost','user','p@ss'))
                {
                        if (!@mysql_select_db ('web_site'))
                        {
                                die('<p> Could not select the database brcause:<b>'. mysql_error() .'</b></p>');
                        }
                }else{
                        die('<p>Could not connect to MYSQL because:<b>' . mysql_error() . '</b></p>');
                        }


$queryb = "UPDATE misc_entries SET title='{$_POST['title']}',entry='{$_POST['entry']}' WHERE id={$_POST['id']}";


if (@mysql_query ($queryb)){
                        echo "<meta http-equiv='refresh' content='0;URL=edmp.php'>";
                        }else{
                        print"<p>Could not add the entry because:<b>" .mysql_error() . "</b>. The query was $query.</p>";
                }

mysql_close();
}

?>

 

Tha problem is that when i press the save button it doesn't update the db.

 

Also i have to add  here that i do the exactly the same thing with another table and there it works fine ...

 

Can you see any mistake here?

 

Thanks...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.