What is the difference between variables and strings in PHP, and how does it affect querying databases?

Variables in PHP are used to store data values, while strings are a specific type of variable that holds text. When querying databases in PHP, it is important to properly handle variables and strings to ensure the query is executed correctly. Variables should be concatenated into the query string, while strings should be properly escaped to prevent SQL injection attacks.

// Example of querying a database using variables and strings in PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Example of using variables in a query
$user_id = 1;
$sql = "SELECT * FROM users WHERE id = " . $user_id;

$result = $conn->query($sql);

// Example of using strings in a query (with proper escaping)
$username = "John";
$username = $conn->real_escape_string($username);
$sql = "SELECT * FROM users WHERE username = '$username'";

$result = $conn->query($sql);

// Close connection
$conn->close();