How can I pass a variable into SQL where clause using PHP?
Go to solution
Solved by vorticalbox,
Db.php
<?php class db { private static $handle; public static function connect($host, $username, $password, $db){ self::$handle = new PDO("mysql:host={$host};dbname={$db}", $username, $password); self::$handle->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); } public static function query($sql, $args=null){ $sth = self::$handle->prepare($sql); $sth->execute($args); return $sth; } //end of class } //enter your database information here. host, username, password, DB name db::connect("host", "username", "password", "database"); ?>
then your php
require('db.php');
$sql = db::query("select ID from student_tbl where firstName=:n limit 1",
array(":n" => $name));
$row = $row->fetch(PDO::FETCH_ASSOC);
//row now contains an dict of your data
echo $row['ID'];
If you need more just but more field=:c to the query and then add , 'c' => $variable to the array
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now