StressedStudent StressedStudent - 1 year ago 50
MySQL Question

My sql query in php updates all my entries not just one

so i have this code in my main page:

<form action="update.php" method="post">

ID: <input type="text" name="ID" /><br>
Name: <input type="text" name="Name" /><br>
Details: <input type="text" name="Details" /><br>
Seasons: <input type="text" name="Seasons" /><br>
Price: <input type="text" name="Price" /><br>
Image: <input type="text" name="Image" /><br>

<input type="submit" value="Update" /><br><br>


and this is in my update.php page:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "series";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

$sql = "UPDATE series SET ID=('$_POST[ID]'), Name=('$_POST[Name]'), Details=('$_POST[Details]'), Seasons=('$_POST[Seasons]'), Price=('$_POST[Price]'), Image=('$_POST[Image]')";

if (mysqli_query($conn, $sql)) {
header( 'Location: i.php' );
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);


I cannot make it update a single entry in the db, every time i input something and try to update, it updates all the entries, not just the one i wanted. Can someone help me with a where condition, i dont know how to write it

Answer Source

In form first you fetch database record with unique id of the record which you want to update. I have used $id variable with static value. You can change it by yourself

<form action="update.php" method="post">
$id = 1; //suppose your id of your database is 1. You can change it.
$res = mysqli_query($conn, "SELECT * FROM series WHERE ID=$id");//You can use id of you record
while($row = mysqli_fetch_array($res)){
<input type="hidden" name="ID" value="<?php echo $id; ?>" /><br><!--This is id of record which you want to update-->
Name: <input type="text" name="Name" value="<?php echo $row['Name']; ?>" /><br>
Details: <input type="text" name="Details" value="<?php echo $row['Details']; ?>" /><br>
Seasons: <input type="text" name="Seasons" value="<?php echo $row['Seasons']; ?>" /><br>
Price: <input type="text" name="Price" value="<?php echo $row['Price']; ?>" /><br>
Image: <input type="text" name="Image" value="<?php echo $row['Image']; ?>" /><br>

<input type="submit" value="Update" /><br><br>

In your sql query I have supposed ID is unique id of your record and added a condition with WHERE clause which you want to update.

$sql = "UPDATE series SET Name=('$_POST[Name]'), Details=('$_POST[Details]'), Seasons=('$_POST[Seasons]'), Price=('$_POST[Price]'), Image=('$_POST[Image]') WHERE ID='$_POST[ID]'";