简体   繁体   中英

Do I need prepared statement on each query?

$query = "SELECT 1 FROM users WHERE username = :username";
$query_params = array(':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}

$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}

This all works, but:

  1. Do I really need prepared statement if the query is just SELECT or SELECT COUNT ?
    Because, if there is no INSERT / UPDATE / DELETE operations on the table - I suppose there is no dangerous of sql injection or spam ?

  2. Do I really need try/catch statement each time I go to database ?

如果您在查询中放入了任何可以以任何方式更改的变量,则您(必须)使用准备好的语句。

There is always a danger of SQL injection even on SELECT statements because someone could terminate the SELECT and append an INSERT statement in the username. However, if you are using mysql_real_escape_string() or else your DB classes escape your values for you then you don't have to worry about try/catch on a SELECT statement. If you have escaped your values this is sufficient for your SQL:

$username = mysql_real_escape_string($username); // escape the string first.
$query = "SELECT 1 FROM users WHERE username = '$username'";

1) No, you don't have to use prepared statements; you could use eg PDO::query and PDO::quote to build up a query using string concatenation. HOWEVER -- YES, any time you're using externally-supplied strings, there is a risk of damage from SQL injection, even if you're just doing a SELECT. For example, an attacker could try to run two statements in one by using a ";" in the supplied string. The PDO::quote is another way to safeguard against this.

2) You could throw the error out of your calling code, but somewhere you'll have to consider error handling.

As far as connection to database goes this is the only approach you need. Try and Catch: (if you are using MySql database )

try {
    $conn = new PDO('mysql:host=localhost;dbname=DBNAME', 'USER', 'PASS', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Plus, there is a built-in count query for count:

$affected_rows = $stmt->rowCount();

Here is a good tutorial, if you never knew

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM