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 trial

PHP

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Getting SQL syntax error through PDO query.

I'm not quite sure what I'm doing wrong here. My SQL syntax looks to me.

I keep getting the lovely:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''users''.

I get the error after I call get(): I only have one table and it's called users.

$con = connect($config);
//DB IS CONNECTING FINE

if( $con ) {
  $users = get('users', $con);
  foreach($users as $user){
    print_r($user);
  }
} else {
    echo 'Could not connect to database.';
}

Here is my get() logic. I have looked over many times and don't understand how I'm getting thrown an SQL syntax error.

$con = connect($config);
//DB IS CONNECTING FINE

function get($tableName, $con) {
        $result = $con->prepare("SELECT * FROM :tablename");
        $result->bindParam(':tablename', $tableName);
        $result->execute();
    }
Łukasz Czuliński
Łukasz Czuliński
8,646 Points

So I ended up getting this to work with a query and not a prepared statement like so:

function get($tableName, $con) {
    return $con->query("SELECT * FROM " . $tableName);
}

Since there's no form entry from the user here I realize we technically don't need to bind parameters, but I'd still like to know where I went wrong if anyone knows.

1 Answer

Table and column names cannot be passed as bind variables. Use bind variables for the values in WHERE clauses.

Łukasz Czuliński
Łukasz Czuliński
8,646 Points

Amazing. I spent most of today looking for a solution and couldn't find one.

I never thought to actually ask in the searches if table names are valid bind variables. It just seemed obvious that they were.