How do I turn this code into a code that works with PDO?
if($_POST['name']=='home_title'){
$id=$_POST['pk'];
$home_title=$_POST['value'];
$result=mysql_query("SELECT COUNT(*) as count FROM sw_configuration WHERE id=$id") or die(mysql_error());
$count= mysql_fetch_row($result);
if($count[0]==0){
mysql_query("INSERT INTO sw_configuration(id,home_title) VALUES('".$id."','".$home_title."')") or die(mysql_error());
}else{
mysql_query("UPDATE sw_configuration SET home_title='".$home_title."' WHERE id=$id") or die(mysql_error());
}
}
Simply using PDO is not enough to make your script secure from SQL injection attacks. You still need to make sure all of your user-supplied variables are either properly quoted or better yet, use prepared statements with bound parameters, which is the preferred way. If you don't do this, there is no difference security-wise between using PDO and the regular mysql_*
functions. Here is an example of how you can do it:
$stmt = $dbh->prepare("INSERT INTO sw_configuration(id,home_title)
VALUES(:id,:home_title)");
$stmt->bindValue(':id', $id);
$stmt->bindValue(':home_title', $home_title);
$stmt->execute();
Or if you need to select a value:
$stmt = $dbh->prepare("SELECT COUNT(*)
FROM sw_configuration WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$count = $stmt->fetchColumn();