veenu
veenu

Reputation: 53

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.

Upvotes: 2

Views: 19521

Answers (2)

aezaz vahora
aezaz vahora

Reputation: 21

write after Connection code below statement

$fieldname = $_POST[ 'fieldname' ];

Upvotes: 0

zkemppel
zkemppel

Reputation: 238

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.

Upvotes: 6

Related Questions