Tags
Asked 2 years ago
17 Jun 2021
Views 228
Bonnie

Bonnie posted

string variable in WHERE clause MySQL,PHP

string variable in WHERE clause MySQL,PHP
fatso

fatso
answered Apr 28 '23 00:00

To use a string variable in the WHERE clause of a MySQL query in PHP, you can include the variable in the SQL query string using concatenation and quotes. Here's an example:



$variable = "some_value";
$query = "SELECT * FROM my_table WHERE column1 = '" . $variable . "'";

$result = mysqli_query($connection, $query);

In this example, the $variable PHP variable contains the string value you want to filter on, and the $query variable is the SQL query string that includes the WHERE clause. The . operator i s used to concatenate the variable value with the rest of the SQL query string, and the single quotes around the variable value ensure that it is properly formatted as a string in the SQL query.

Note that if the value of $variable comes from user input, it should be properly escaped and sanitized to prevent SQL injection attacks. You can use the mysqli_real_escape_string() function to escape any user input used in the query.

Also, be sure to properly quote and format the variable in the SQL query string. If the variable is a string, it should be enclosed in quotes in the query. If the variable is an integer or other numeric type, it should not be enclosed in quotes.
Post Answer