Skip to content
Advertisement

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

I have a php variable that I want to fetch another field in database using this variable in my where clause.

My code:

require("conn.php");
$module = $_POST[ 'postmodule' ];
$query = "SELECT width FROM modules WHERE code = $module";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
echo $row['width'];

But this is printing me nothing. Don’t know where I am going wrong but any help would be appreciated.

Advertisement

Answer

You can either break the string and concatenate the variable with ".."

require("conn.php");
$module = $_POST[ 'postmodule' ];
$query = "SELECT width FROM modules WHERE code = '".$module."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
echo $row['width'];

Or you could wrap the variable in {} within the string, as long as the string is wrapped in double quotes.

require("conn.php");
$module = $_POST[ 'postmodule' ];
$query = "SELECT width FROM modules WHERE code = '{$module}'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
echo $row['width'];

Also, if $module is a string you will need to wrap the variable in single quotes as I did above.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement