Jump to content

pdo mysql, code safe from injection?


Go to solution Solved by mac_gyver,

Recommended Posts

 is this select query code safe from injection?

try {
	$stmt = $db->prepare("SELECT * FROM posts WHERE key=$key");
	$stmt->execute();
	$row = $stmt->fetch();
} 

notice there is no bind.

$stmt->bindParam(':key', $key);

the reason i am asking is that i have many $key variable in the query and i do not know how to use bind in a query such as this...

SELECT count(*) FROM posts WHERE MATCH (file) AGAINST 
('$key' IN BOOLEAN MODE) OR MATCH (user) AGAINST ('$key' IN BOOLEAN MODE)

the $key is not an array and the $key does not change it's value.

Edited by kalster
Link to comment
https://forums.phpfreaks.com/topic/293662-pdo-mysql-code-safe-from-injection/
Share on other sites

  • Solution

this may actually be a good place to use a ? place-holder rather than a named one so that you don't need to generate anything special in the sql query syntax. you would only need to know the range of integer numbered indexes they are in the bind statement.

if you are dynamically building the query, you would just add one element to a $param array for each place holder. if you have a bunch of statically written queries, you would build the $param array to match the place holders in each query.

i/we don't see what problem you are having applying this to your code since you haven't shown us any actual code/context.

$key = "+some +keywords -here"; // a sample boolean mode query string that's been input to your code

// the params array for a query that has 3 place holders - :key1, :key2, :key3
$params = array(':key1'=>$key, ':key2'=>$key, ':key3'=>$key); // note this is also of the format that you could use $stmt->execute($params)

// bind the parameters
foreach($params as $k=>$v){
  $stmt->bindParam($k, $v);
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.