Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFurquan Ahmad
5,148 PointsSQL query doesn't work if try an AND statement
I'm trying to select multiple conditions in my sql database, but it only works with one condition.
This query works, but when i try and to another AND statement it doesn't work
<?php
$stmt = $db->prepare("SELECT * FROM paststudent WHERE subject1 =:subject1 AND grade1=:grade1");
$stmt->execute(array(':subject1' => $subject1, ':grade1' => $grade1));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
I'm trying to do
<?php
$stmt = $db->prepare("SELECT * FROM paststudent WHERE subject1 =:subject1 AND grade1=:grade1 AND subject2 =:subject2 AND grade2 =:grade2 ");
$stmt->execute(array(':subject1' => $subject1, ':grade1' => $grade1, 'subject2' => $subject2, ':grade2' => $grade2));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
1 Answer
Andrew Shook
31,709 PointsYou need to add a colon in front of subject2 in you execute statement.
<?php
$stmt = $db->prepare("SELECT * FROM paststudent WHERE subject1 =:subject1 AND grade1=:grade1 AND subject2 =:subject2 AND grade2 =:grade2 ");
/*
you nee to change this:
$stmt->execute(array(':subject1' => $subject1, ':grade1' => $grade1, 'subject2' => $subject2, ':grade2' => $grade2));
to this*/
$stmt->execute(array(':subject1' => $subject1, ':grade1' => $grade1, ':subject2' => $subject2, ':grade2' => $grade2));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);