I am trying to get the $w['id'] value for a mysql row and pass it to another page using a hidden input field and variable $blog_id. Here is the code for the first page:
$query = "SELECT * FROM blog WHERE username = '$username' ORDER BY created_date DESC;";
$result = $mysqli->query($query);
$rows = resultToArray($result);
// var_dump($rows);
foreach($rows as $r => $w) {
echo "<tr>
";
echo "<td>{$w['title']}
";
echo "<td>{$w['id']}
";
echo "<td>{$w['created_date']}</td>
";
echo "<td>{$w['updated_date']}</td>
";
echo "<td style=\"border:none\">{$w['template']}</td>
";
$blog_id = $w['id'];
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />
";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"view\">View</button></td>
";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"edit\">Edit</button></td>
";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"delete\"><font color=\"red\">Delete</font></button></td>";
echo "</tr>
";
}
?>
In my html table the values echo correctly but when I try to grab the $w['id'] value and pass it using, say, the edit button to the next page the value is always the lowest id value in the mysql table.
The code for the critical part in the second page is:
sec_session_start();
$username = $_SESSION['username'];
// $blog_id = $_SESSION['blog_id'];
if(isset ($_POST['edit'])) {
$blog_id = $_POST['id'];
$result = $mysqli->query("SELECT * FROM blog WHERE id = '$blog_id'");
if($result->num_rows > 0) {
$rows = resultToArray($result);
foreach($rows as $r => $w) {
?>
<body id="blog_editor">
<?php var_dump($_POST); ?>
The value of var_dump($_POST) is always ["id"]=>string(2) "43" whereas the foreach loop on the first page produces lots of different IDs. Does anybody know what I am doing wrong or have an alternative way of doing the same kind of thing which might work?
You use a foreach
and echo many different id
.
I don't see any SUBMIT
button or <form>
tag.
What you can do is, inside the foreach loop, create a form with is own button:
<?php
foreach($rows as $r => $w) {
echo '<form action="page.php" ...>
echo ....
echo '<input type="submit">
}
?>
OR if you have multiple results inside one only form then you have to change the name
of your element (which will be later give the value to `$_POST['id']) every time the loop loops.
To do this change this line:
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />
";
1) to this:
echo "<input type='hidden' name='id".$blog_id."' value='$blog_id' />
";
and then when you call $_POST
you'll have $_POST['idXX']
where XX = number of the ID
2) or TO this to create an array with all IDs on it:
echo "<input type='hidden' name='id[]' value='$blog_id' />
";
and then $_POST['id']
will be an array