PHP PDO prepared statements

后端 未结 1 1130
你的背包
你的背包 2020-11-22 07:44

I was told today that I should really be using PDO and prepared statements in my application. Whilst I understand the benefits, I am struggling to understand how I implement

相关标签:
1条回答
  • 2020-11-22 08:16

    There are two great examples on the pdo::prepare() documentation.

    I have included them here and simplified them a bit.

    This one uses ? parameters. $dbh is basically a PDO object. And what you are doing is putting the values 150 and 'red' into the first and second question mark respectively.

    /* Execute a prepared statement by passing an array of values */
    $sth = $dbh->prepare('SELECT name, colour, calories
                          FROM fruit
                          WHERE calories < ? AND colour = ?');
    
    $sth->execute(array(150, 'red'));
    
    $red = $sth->fetchAll();
    

    This one uses named parameters and is a bit more complex.

    /* Execute a prepared statement by passing an array of values */
    $sql = 'SELECT name, colour, calories
            FROM fruit
            WHERE calories < :calories AND colour = :colour';
    
    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(':calories' => 150, ':colour' => 'red'));
    
    $red = $sth->fetchAll();
    
    0 讨论(0)
提交回复
热议问题