Reputation: 346
I have the following code:
while ($content = mysql_fetch_array($content2)){
echo $content[0];
session_start();
$_SESSION['content'] = $content[0];
?>
<br />
<a href="edit.php"> Edit post. </a>
<br /> <br />
<?php
}
It fetches and displays all posts from a blog system database, and you can click on "Edit." below each post. What I want to do is pass the content of that post to my edit.php script.
The problem is, whichever "Edit" button I click on, this will always pass the content of my last post, not the content of the post above that "Edit" button.
Now, I can see why that might be: The whole loop will be executed before I click on any button, and the value stored in $_SESSION['content'] will always be the value from the loop's last iteration. Am I right?
Maybe I shouldn't be using SESSION. Is there a better approach? How can I pass the "right" value of $content[0] to my edit.php script?
Upvotes: 0
Views: 101
Reputation: 1000
The reason why the edit button is always getting the last post is because you are overriding the content variable in the session on each loop.
I am not sure what information you are getting from the database, but you should have a unique ID in the database for each post which you grab in the array as well. If this does not exists, I would strongly recommend making a change in your table as it will simplify your process.
while ($content = mysql_fetch_assoc($content2))
{
echo $content['postText'] . "<br />";
echo '<a href="edit.php?postId=' . $content['postId'] . '"> Edit post. </a><br /><br />';
}
You will then have to set up the edit page to grab the id $_GET['postId']
and grab the proper content from the database.
Upvotes: 2
Reputation: 9315
You code must be improved, your logic isn't good. First of all, you don't need to use a session var, one alternative to do this is passing the post ID using a GET argument, something like this:
while ( $content = mysql_fetch_array($content2) )
{
$post_content = $content[0];
$post_id = $content[1];
echo $post_content . '<br /> <a href="edit.php?postId=' . $post_id . '"> Edit post. </a> <br /> <br />';
}
Then, in edit.php
you will retrieve the $_GET['postId']
and load the post content to be updated.
Upvotes: 1
Reputation: 469
This would be your best bet if you are ready to go for GET commands. See the code below :
$content = mysql_fetch_array($content2);
foreach($content as $key => $val) {
echo "<a href=edit.php?id=$val['id']>$val['name']</a>";
}
Just a quick fix.
Replace $val['id'] with the column name of uniqueID and $val['name'] with the column name of the post.
Upvotes: 0