I am trying to create a to-do list for practice. When I look through the results I get back from the database, I see all of the results in order with a complete
button and delete
anchor tag. That part works fine but whenever I click on the complete button I only update the third row. Even if I try to click complete on the second or first row only the third row gets updated.
I tried using get_result
instead of bind_result
, I tried using anchor tags, I tried using fetch_assoc()
instead of fetch()
and I tried changing my query multiple times but nothing helped. I've been searching answers on here since last night and still nothing. Any help please ?
$addItem = $_POST['add_item'] ?? '';
$userLoggedIn = $_SESSION['session_user_id'];
$counter = 1;
echo $userLoggedIn . "'s list<br><br>";
$user_query = $con->prepare('SELECT item_id, username, item_name FROM lists WHERE username = ?
ORDER BY item_id ASC');
$user_query->bind_param("s", $userLoggedIn);
$user_query->execute();
/* Store the result (to get properties) */
$user_query->store_result();
/* Get the number of rows */
$num_of_rows = $user_query->num_rows;
/* Bind the result to variables */
$user_query->bind_result($itemId, $username, $itemAdded);
/*while ($row = $data_query_result->fetch_assoc()) {
$itemId = $row['item_id'];
$username = $row['username'];
$itemAdded = $row['item_name'];
} */
while ($user_query->fetch()) {
echo "<p>" . $counter . ". " . $itemAdded . $itemId .
"<form action='index.php' method='POST'><button type='submit'
name='completed_button' value=". $itemId .">" .
$itemAdded . " </button></form>" .
" <a href='#'>Delete</a>" . "</p>";
$counter++;
}
$user_query->free_result();
$user_query->close();
if (isset($_POST['add_item_button'])) {
$stmt = $con->prepare("INSERT INTO lists (username, item_name) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $addItem);
$stmt->execute();
}
if (isset($_POST['completed_button'])) {
$user_data_query = $con->prepare('UPDATE lists SET completed = "1" WHERE item_id = ?');
$user_data_query->bind_param("i", $_POST['item_id']);
$user_data_query->execute();
//$updateCompleted = "UPDATE lists SET completed = '1' WHERE item_id = " . $itemId . " ";
//$query2 = $mysql->query($updateCompleted);
}