How can variables be effectively used in SQL queries for inserting and updating data in PHP?

When inserting or updating data in SQL queries in PHP, variables can be effectively used to dynamically pass values to the query. This allows for more flexibility and security, as it helps prevent SQL injection attacks and makes the code easier to maintain. To use variables in SQL queries, simply assign the values to variables and then include those variables in the query string.

// Example of using variables in SQL queries for inserting data
$name = "John Doe";
$email = "johndoe@example.com";

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$result = mysqli_query($connection, $sql);

// Example of using variables in SQL queries for updating data
$id = 1;
$newEmail = "newemail@example.com";

$sql = "UPDATE users SET email = '$newEmail' WHERE id = $id";
$result = mysqli_query($connection, $sql);