I am having a bit of a problem binding a value with PDO and PHP. When I replace the values with variables the script returns the proper result but for some reason I can’t get this to work.
// Connect to database in function on different page
function db1() {
try {
$pdo = new PDO("mysql:host=localhost;dbname=**********", '**********', '**********');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
$pdo = null;
} catch (PDOException $e) {
die($e->getMessage());
}
}
// Scrit with problems
$db = db1();
$query = $db->prepare("SELECT column1, column2, column3, column4 FROM table_name WHERE (column4=2 OR column4=3) AND column5=:col1 AND column6=:col2"); // Prepare the statement to prevent any SQL injection
$query->bindValue(':col1', $var1, PDO::PARAM_INT);
$query->bindValue(':col2', $var2, PDO::PARAM_STR);
$query->execute();
// I also tried the following.
// $query->execute(array(':col1' => $var1, ':col2' => $var2));
// Fetch result row
$row = $query->fetch(PDO::FETCH_ASSOC);
Any ideas?
UPDATE
Did var_dump before and after the query. var1 = string(1) “2” and var2 = string(1) “1”
Removed $pdo = null;
Except for the
$pdo = nullline which is after areturnand therefore never executed, and the$db = $db1()where the function is used as a variable, the code hasn’t anything obviously wrong. Since you say that replacing the bindings with variables work, I assume the last is a typo.So I suggest you try and
var_dumpwhat the values of$var1and$var2are at that point in the script.UPDATE
I have duplicated the setup like this
Then I created a first table like this
and then like this
and I tried defining
$var1and$var2as 1,2 (integer) and “1”,”2″ (strings).It always worked, i.e., I expected to get a single row as output, and I did:
At this point I think the only possibility left is something strange in the database content.
Therefore I also expect the test below, on your system, not to work, i.e. not to return the desired row: