Reputation: 103
So am getting further into my learning and have ran into an issue with this:
Updating records from my index page, I am able to insert and delete but struggling to update them.
So this show the records with links to update or delete:
<?php
$result = mysqli_query($con,"SELECT * FROM items");
$y = 'id';
while($row = mysqli_fetch_array($result)) {
echo $row['added'] . $row['content'] . $row[$y];
echo "<br>";
echo "Mark as complete";
echo "<br>";
echo "<a href='delete.php?id=" . $row['id'] . "'>Delete Item</a>";
echo "<br>";
echo "<a href='update.php?id=" . $row['id'] . "'>Edit Item</a>";
echo "<br>";
echo "<br>";
}
mysqli_close($con);
?>
When the user clicks on edit it passes over the id of that item which is good but my form to update the records is behaving strangely, the submit button seems to have disappeared but does appear if I remove the php, here is the update form:
<form action="insertupdate.php" method="post">
Content: <input type="text" name="content">
<input type="hidden" name="id" value='<?php $_POST ('id'); ?>'>
<button>dsfsd</button>
</form>
And here the script for updating, but it does not appear to be making the changes:
mysqli_query($con,"UPDATE items SET content='blah blah blah' WHERE id=id");
if (isset($_POST['content'])) {
mysqli_query($con,"UPDATE items SET content='".mysqli_real_escape_string($con, $_POST['content'])."' WHERE id=".($_POST['id']));
}
header('Location: index.php');
mysqli_close($con);
Upvotes: 1
Views: 868
Reputation: 1718
Replace
<input type="hidden" name="id" value='<?php $_POST ('id'); ?>'>
<button>dsfsd</button>
By
<input type="hidden" name="id" value="<?php echo $_POST['id']; ?>" />
<input type="submit" value="Valid" />
You script don't get ID, so it will never work.
For your query :
mysqli_query($con, "UPDATE items SET content = '".mysqli_real_escape_string($con, $_POST['content'])."' WHERE id = ".intval($_POST['id']));
intval()
will convert $_POST['id']
into a number, so you will be sure a string or special character will not be entered.
Upvotes: 1
Reputation: 335
I used to get errors like this all the time. Fortunately, there is some very good error handling in MySQL. Add this else condition in the if with the query:
if (isset($_POST['content'])) {
mysqli_query($con,"UPDATE items SET content='".mysqli_real_escape_string($con, $_POST['content'])."' WHERE id='".($_POST['id'])."'");
} else {
mysqli_error($con);
}
Oh and to directly fix your problem, it looks like you need quotes around the id part of the query:
mysqli_query($con,"UPDATE items SET content='".mysqli_real_escape_string($con, $_POST['content'])."' WHERE id='".($_POST['id'])."'");
Upvotes: 0