Tags
Asked 3 years ago
17 Jun 2021
Views 273
Johnson

Johnson posted

How to pass a php variable in WHERE clause of SELECT statement

How to pass a php variable in WHERE clause of SELECT statement
rajiv

rajiv
answered Apr 28 '23 00:00

To pass a PHP variable in the WHERE clause of a SELECT statement, you can include the variable in the SQL query string using concatenation. 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 value you want to filter on, and the $query variable is the SQL query string that includes the WHERE clause. The . operator is used to concatenate the variable value with the rest of the SQL query string.

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 careful 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