Edit and delete by id

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Mirux
Forum Commoner
Posts: 29
Joined: Sun May 13, 2007 7:11 pm

Edit and delete by id

Post by Mirux »

Howdy, I'm a new here and I'd like to start using these forums to learn more and more about PHP.

Well, my question is: I've been working on a simple project which basically saves info into a database through a form.

I'll post the codes here and explain what it is needed.

addnews.php

Code: Select all

<!-- Formulario HTML -->
<table border='0' cellpadding='2' cellpadding='2'>
<form name='news' method='POST'>
<tr>
<td>Title: </td><td><input type='text' name='title'></td>
</tr><br>
<tr>
<td>Author: </td><td><input type='text' name='author'></td>
</tr>
</table><br>
<textarea name='text' cols='90' rows='20' wrap='hard'></textarea><br>
<input type='submit' name='submit' value='Add new'><br>
</form>
<!-- Intrucciones PHP -->
<?php
$date= time();
if ($submit)
{
	include ("dbconnect.php"); // We connect to the db and select the table.
	mysql_query("INSERT INTO $table (title, date, text, author) VALUES ('$title', '$date', '$text', '$author')");
	mysql_close();
	echo "The information was successfuly saved."; // This message will be printed if everything went alright so far.
}
else
{
	echo "There was an error saving your info in the database, try again later."; // This message will be printed if there was an error.
}
?>
This is basically a form with a tiny php code inside which saves the info into a database. I think the code is pretty much clean, if it's not just let me know. I'd be glad to read some suggestions.

Then I made this script to output the info.

news.php

Code: Select all

<html>
<h2>Database information</h2>
<p></p>
</html>
<?php
include ("dbconnect.php");
$result= mysql_query("SELECT * FROM $table ORDER BY date DESC");
$num= mysql_num_rows($result);
$i=0;
while ($i < $num)
{
	$row= mysql_fetch_array($result);
	echo date("d/m/Y", $row['date']) ." - ". $row['title'] ."<br />". $row['text'] ."<br />~ ". $row['author']; 
$i++;
}
mysql_close();
?>
Same thing here, clear like water.

The problem is that I don't know how or where to specify the 'id' field to each new I add. "Why do I want to do this?" It's the only way I see I can make an edit or delete option for this system. What I mean is, I'd like to add an option to edit a new already stored in the database, but my problem is that I don't know how to select a new before I edit.

For example, If I have 3 news, id=1,2,3. I'd like to edit the new id=2. How do I do this? I know how to code it but I don't know where to put or where should I specify the id for each new. This is the same for DELETE a new.

Please, someone help me. I'm just stuck with this!

Thank you very much.

PD: I'm sorry for my bad english.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

Hi,

If I understand you correctly, you want to specify the record you require...yes?

Anyway, use "where" in the query:

i.e.

Code: Select all

$query=mysql_query("SELECT * FROM tblName WHERE newsId = '$id'") or die(mysql_error());
or alternatively if you want to delete a specific record:

Code: Select all

$query=mysql_query("DELETE FROM tblName WHERE newsId = '$id'") or die(mysql_error());
Is this what you are after?
Mirux
Forum Commoner
Posts: 29
Joined: Sun May 13, 2007 7:11 pm

Post by Mirux »

Okay but where should I define the $id? Because I assume I gotta put a link to 'editnew.php' in 'news.php' (echo part) which will get the right record to edit?

Imagine it outputs 3 news stored in the db. I want a graphical way to select the new id=2 and edit it or delete it for example.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

Ok,

Say you have a list output by a while loop

e.g.

Code: Select all

<table width="100%">
$query=mysql_query("SELECT * FROM table ORDER BY whatever") or die(mysql_error());

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

?>
<tr>
<td><input name="newsItem" value="<? echo $newsId; ?>"><? echo $newsItem; ?> /></td>
<td><a href="editItem.php?id=<? echo $newsId; ?>">Edit Item</a></td>
</tr>
<?
}
?>
</table>
For each row that is extracted within the loop the corresponding id is extracted also. This corresponding id has been included in the href link as a parameter variable named id.

When editItem.php is opened simpy write a script that uses $_REQUEST['id'] to get the correct record in a select query (just liek the one i posted earlier).
Mirux
Forum Commoner
Posts: 29
Joined: Sun May 13, 2007 7:11 pm

Post by Mirux »

I am really confused. I understand it but not entirely. I know the loop returns every news id but I don't want to print them. I just want to link it with the edit.php file.

I better go to sleep now, my brain is just stupid tonight. ;[ I'll post more later. Thanks for your help so far ace.
Mirux
Forum Commoner
Posts: 29
Joined: Sun May 13, 2007 7:11 pm

Post by Mirux »

HAAAAA! I made it work! YESSSSS

Look at the code:

news.php

Code: Select all

<html>
<div align='justify'>
<h2>Database information</h2>
<p></p>
<?php
include ("dbconnect.php");
if (!isset($cmd))
{
$result= mysql_query("SELECT * FROM $table ORDER BY date DESC");
while ($row= mysql_fetch_array($result))
{
	$id= $row['id'];
	echo "<b>". date("d/m/Y", $row['date']) ." - ". $row['title'] ."</b>". "<br />". $row['text'] ."<br />~ ". $row['author']. "<br /><a href='editnews.php?cmd=edit&id=$id'>Edit</a>". "<p>";
}
}
?>
</div>
</html>
and now:

editnews.php

Code: Select all

<?php
if ($_GET['cmd'] == "edit" || $_POST['cmd'] == "edit")
{
	if (!isset($_POST['submit']))
	{
		include ("dbconnect.php");
		$id= $_GET['id'];
		$query= "SELECT * FROM $table WHERE id='$id'";
		$result= mysql_query($query) or die (mysql_error());
		$row2= mysql_fetch_array($result);
?>
<table border='0' cellpadding='2' cellpadding='2'>
<form name='news' method='POST' action='editnews.php'>
<input type='hidden' name='cmd' value='edit'>
<input type='hidden' name='id' value=<? echo $row2['id'] ?>>
<tr>
<td>Title: </td><td><input type='text' name='title' value='<? echo $row2["title"] ?>'></td>
</tr><br>
<tr>
<td>Author: </td><td><input type='text' name='author' value='<? echo $row2["author"] ?>'></td>
</tr>
</table><br>
<textarea name='text' cols='90' rows='20' wrap='hard'><? echo $row2["text"] ?></textarea><br>
<input type='submit' name='submit' value='Edit'><br>
</form>
<? } } ?>
This works fine for me. Now I gotta code the updating script which is not that hard. I just was confused with the $id and 'id' and id hidden and stuff like that.
Mirux
Forum Commoner
Posts: 29
Joined: Sun May 13, 2007 7:11 pm

Post by Mirux »

Wow, I just removed a lot of bollocks in my code like the cmd stuff, not necessary.

Thanks aceconcept, I really appreciate your time. :)
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

no worries.

Wasn't entirely sure what your overall objective was.

Anyway, well done.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Might I suggest also running your $_GET and $_POST vars through isset() or empty() before checking if they are equal to something? This rids you of those pesky undefined index errors. Also, you can do this:

Code: Select all

<html>
<div align='justify'>
<h2>Database information</h2>
<?php
include 'dbconnect.php';
if (!isset($cmd))
{
    // This really should have some error checking on this
    $result= mysql_query("SELECT * FROM $table ORDER BY date DESC");

    while ($row= mysql_fetch_array($result))
    {
        echo '<b>' . date('d/m/Y', $row['date']) . ' - '. $row['title'] .'</b><br />'. $row['text'] .'<br />~ '. $row['author']. '<br />
            <a href="editnews.php?cmd=edit&id=' . $row['id'] . '">Edit</a><p>';
    }
}
?>
</div>
</html>
Adrianc333
Forum Newbie
Posts: 14
Joined: Sat Feb 17, 2007 5:44 am
Location: South Yorkshire, UK

Post by Adrianc333 »

You should look-up the function, mysql_real_escape_string();

Clean user inputs.
(At the bottom of the mysql_real_escape_string documentation, there will be links to others functions you may find helpful)
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Just to provide a link... mysql_real_escape_string

Also a couple of comments. Whenever you are dealing with php is is good practice to use '<?php' and '?>' rather than simply '<?' and '?>'. The reason is simply the fact that '<?' relies on a certain configuration setting which may not otherwise be available (short tags).

Code: Select all

$result= mysql_query($query) or die (mysql_error());
Whilst this is good and is essential when developing you may want to have a more meaningful output displayed to users on a live system. It is not a good idea to output the mysql error message directly in a live system. One method might be to check if a $_GET['debug'] value is 76. If it is display the error message otherwise simply output "Unable to retrieve information from the database". (The number 76 picked at random, I don't normally use simply 1 as people may guess it).

Finally: Welcome to these forums. Hope you find your time with us profitable and enjoyable.
Post Reply