Is it possible to use variables instead of a literal in prepared statements? If so, how?

98 views Asked by At

What I mean is, my current prepared statement starts like this:

$stmt = $bd->prepare("SELECT Beer_Name FROM Beer WHERE Gluten = ?");

But is is possible to do it like this(below)? Because I've tried several ways and none have been successful.

$stmt = $bd->prepare("'.$sql.'");

I ask because I'm trying to create a function, as I am coding a website that uses a lot of queries.

<?php

include('connection.php');


    global $sql;
    global $ready;


        $sql = 'SELECT Beer_Name FROM Beer WHERE Gluten = ?';
        $ready = "Yes";


function bindingHelper($ready, $sql) {

            $stmt = $bd->prepare($sql);
            $stmt->bind_param("s", $ready);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($beer_name);
            $stmt->fetch();

            echo($beer_name);
}

bindingHelper($ready, $sql);

?>
2

There are 2 answers

0
Funk Forty Niner On BEST ANSWER

I didn't notice that actually, and yes I have a fair idea. We all make mistakes. I moved include('connection.php'); inside the function and now it works perfectly. Please add this as an answer and I'll accept. – user3822332

As per OP's request.

what you have here is a variable scope issue.

therefore, your variables aren't being accessed from the function.

  • Amidst the comments under their question to establish the solution.

Error checking links references:

7
Marc B On

PHP strings 101:

You have this:

$sql = "SELECT 'foo'";
$stmt = $bd->prepare("'.$sql.'");

You will be sending this literal query to the database:

   '.SELECT 'foo'.'
   ^^------------^^- quotes and . from the prepare() call
     ^^^^^^^^^^^^--- contents of $sql

Since the database has absolutely NO idea how this string was created, it takes it at face value:

  '.SELECT 'foo'.'
  ^^^^^^^^^^--- string literal
            ^^^--- unknown keyword
               ^^^--- string literal

None of that is valid sql, therefore the entire "query" is invalid.