PDO Database access WHERE title = $title

后端 未结 5 1444
無奈伤痛
無奈伤痛 2021-01-26 15:03

I\'m trying to learn to use PDO instead of MySQLi for database access and I\'m having trouble selecting data from the database. I want to use:

$STH = $DBH->qu         


        
相关标签:
5条回答
  • 2021-01-26 15:38

    remove the variable out of the sql statement because its a php variable

    $STH = $DBH->query('SELECT * FROM ratings WHERE title=' . $title . 'ORDER BY date ASC');
    
    0 讨论(0)
  • 2021-01-26 15:42

    Use double quotes instead of single quotes as a parameter of the query-method.

    The reason you're getting this error is because the query-method fails and so the $STH object isn't created. You should implement some error handling.

    0 讨论(0)
  • 2021-01-26 15:50

    Take a look at PDO::prepare and PDOStatement::execute. The safest way to add user content to a query is to prepare a basic statement and bind the parameter to it. Example (note the question mark in the SQL statement):

    $STH = $DBH->query('SELECT * FROM ratings WHERE title=? ORDER BY date ASC');
    $STH->execute( array( $title ) );
    
    while( $row = $STH->fetch( PDO::FETCH_ASSOC ) );
    
    0 讨论(0)
  • 2021-01-26 15:55

    It's likely a SQL syntax error, because you forgot to quote $title. It ended up as bareword in the query (also not even interpolated as string), resulting in an error. And your PDO connection was not configured to report errors. Use ->quote() on arguments before the ->query():

    $title = $DBH->quote($title);
    $STH = $DBH->query("SELECT * FROM ratings WHERE title=$title ");
    

    Or better yet, use parameterized SQL:

    $STH = $DBH->prepare("SELECT * FROM ratings WHERE title=? ");
    $STH->execute(array($title));
    
    0 讨论(0)
  • 2021-01-26 15:57
    1. Make PDO throw errors so you can see what exactly goes wrong. See How to squeeze error message out of PDO?

    2. You are probably missing quotes around $title but this scenario really calls for prepared statements instead.

    0 讨论(0)
提交回复
热议问题