ODBC and SQL Server 2008: Can't use prepared statements?

懵懂的女人 提交于 2019-12-13 01:06:28

问题


OK, so I cannot get this to work (either):

$stmt = odbc_prepare($conn, "SELECT * FROM Users WHERE username=?");
odbc_execute($stmt, array($username));
$user = odbc_fetch_object($stmt);


$stmt = $pdo->prepare("SELECT * FROM Users WHERE username=?");
$stmt->execut(array($username));
$user = $stmt->fetchObject();

Both return the same errors:

Warning: odbc_execute(): SQL error: Failed to fetch error message, SQL state HY000 in SQLExecute in user.php on line 24

Anyone know if it's possible to solve this, or are prepared statements off the table? If so, how should guard against SQL injections?


回答1:


I never use the fetchObject method but how about this:

$stmt = $pdo->prepare("SELECT * FROM Users WHERE username=?");
$stmt->bindValue(1, $username);
try{
    $stmt->execute();
    while ($row = $stmt->fetch()){
       // Do whatever.
    }
}catch(PDOException $e){
    echo($e->getMessage());
}

I also notice the single quotes around your question mark ('?'), they shouldn't be there.

In order to use the try/catch stuff you'll need to include this when you create your PDO connection:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

And you might want to add this as well:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Try to use the driver's native prepared statements.


来源:https://stackoverflow.com/questions/13407477/odbc-and-sql-server-2008-cant-use-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!