1

Here I want to add another variable using AND.

$query = $db->prepare("SELECT * 
            FROM messages WHERE Subject_Code = ' ".$_SESSION['sub1']." ' ");

I want to add Week = ' ".$_SESSION["weekS1"]." ' to this query using AND. How can I do it?

0

2 Answers 2

3

PHP PDO supports positional (?) and named (:email) placeholders, the latter always begins from a colon and can be written using letters, digits and underscores only. Also note that no quotes have to be ever used around placeholders.

Eg:

The following becomes

$sql = "SELECT * FROM users WHERE email = '$email' AND status='$status'";

To

$sql = 'SELECT * FROM users WHERE email = ? AND status=?';

OR

$sql = 'SELECT * FROM users WHERE email = :email AND status=:status';

With placeholders, you have to prepare it, using the PDO::prepare() method

To get the query executed, you must run execute() method of this object, passing variables in it, in the form of array

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status=?');
$stmt->execute([$email, $status]);
$user = $stmt->fetch();
// or
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email AND status=:status');
$stmt->execute(['email' => $email, 'status' => $status]);
$user = $stmt->fetch();

Very Good Reference for full tutorial : https://phpdelusions.net/pdo

Sign up to request clarification or add additional context in comments.

1 Comment

Good example. If you want to add conditions incrementally you can have $conds = array() and then append to that and add placeholder values to a secondary array, later combining the query with implode('AND', $conds) to assemble the final clause. PDO makes this pretty easy to do incrementally.
2

If you are using PHP5+, You are supposed to bind your parameters outside of the query string when executing your statement.

Example:

$query = $db->prepare('SELECT * FROM messages WHERE Subject_Code = :subj AND Week = :week')
$query->execute(array(
    ':subj' => $_SESSION['sub1'],
    ':week' => $_SESSION["weekS1"],
));

2 Comments

some great examples of this can be found here: w3schools.com/php/php_mysql_prepared_statements.asp
@Mart Please don't link to third-rate sites like w3schools. The official PHP documentation is up-to-date, more thorough, and has a helpful community comments section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.