I have a table with a date, ID1, ID2 score1 and score2. I am trying to update one row through php when the user has entered the specific date and id's in an html form. I have validated all the user entries. When I run my query it updates all rows in the table instead of just one. Here is a snippet of my code:
include('connect.php');
$q = mysqli_query($dbc, "SELECT * from Game");
while ($row =mysqli_fetch_array($q, MYSQLI_ASSOC))
{
mysqli_query($dbc, "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
}
mysqli_close($dbc);
Shouldn't your where clause be:
WHERE Date = '".$row['Date']."' AND ID1 = '".$row['ID1']."' ");
instead of
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
In the latter you - probably by accident - use some variables as field names as well, which might cause some unwanted issues. For example in your case it's likely to cause an identity condition in your where clause, which will result that all of your rows will get updated.
The WHERE clause in your update statement references only literals. There are no column references.
For debugging, I suggest you concatenate your SQL into a string, and echo it out.
$sql = "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ";
echo $sql;
mysqli_query($dbc, $sql);
With the values of these variables set as shown here:
$date = 'fee'
$row['Date'] = 'fi'
$id = 'fo'
$row['ID1'] = 'fum'
The WHERE
clause in the generated UPDATE update statement would look like this:
WHERE 'fee' = 'fi' AND 'fo' = 'fum'
MySQL sees the values enclosed in single quotes as string literals. There's nothing wrong with that in terms of SQL (it's valid syntax) but it's much more likely you want the WHERE
clause to be more like this:
WHERE fee = 'fi' AND fo = 'fum'
with fee
and fo
as references to columns.