Increment value in MySQL update query
To increment a value in a MySQL update query using PHP, you can use the +=
operator. For example:
<?php
$sql = "UPDATE table_name SET column_name = column_name + 1 WHERE condition";
if ($conn->query($sql) === true) {
// Record updated successfully
} else {
echo "Error updating record: " . $conn->error;
}
This will update the value of column_name
by adding 1 to its current value.
Alternatively, you can use the $conn->query()
function to run the update query and use the mysqli_affected_rows()
function to check if the query was successful:
<?php
$result = $conn->query($sql);
if ($conn->affected_rows > 0) {
// Record updated successfully
} else {
echo "Error updating record: " . $conn->error;
}
Remember to always sanitize any user input to prevent SQL injection attacks. You can use the mysqli_real_escape_string()
function for this purpose.