I’m new at php and I got some problem that I don’t know how to fix, I made
A HTML form that should change the name of a database
<div class="form-group">
<form action="name.php" method="post">
<input type="text" class="form-control" name="name">
<input type="submit" value="Submit" name="submit">
</form>
</div>
HTML form is also connected to PHP edit script
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "tbl_product";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql ="UPDATE tbl_product SET name='$name' WHERE id = ID LIMIT 1";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
header("Refresh:0; url=products.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The script that I run won’t change the database name and if it changes it changes all database names.
For now, looks like the script runs fine but nothing happened.
I need to limit the changing data from database so one change does not change all.
2
Answers
You have to set id in where clause, then it will update only one row matched with the id, You do not need to set LIMIT 1.
You can get id from hidden input in the form.
Your SQL query seems to be faulty. According to a quick test I ran on a local MySQL instance the condition
WHERE id = ID
seems to be always true (it is probably evaluated kind of like1=1
would be. Therefore your query is the same asUPDATE tbl_product SET name='$name' LIMIT 1
and because of that it is updating all records without the LIMIT.Also you are not properly utilizing prepared statements (which is not part of the problem, but you should do it the right way anyway).
That way no SQL injection is possible and you properly use the id in your query and can remove the LIMIT part.
Edit 1 (Redirecting):
Redirecting and sending headers is a whole different topic. Basically you would do it like this (see also this for more details):
Also you can not use
echo
beforeheader
. It will throw an error. See here for more info.Edit 2 (Changing random records):
Changing random records seems to be a strange application, but it would probably work by using this query instead:
You also need to remove the
:id
part from the$stmt->execute
call, since you don’t have an :id parameter in your query anymore.