SQL到PDO用于将表内容传输到另一个表

时间:2014-08-13 22:06:38

标签: php mysql sql pdo

我正在尝试将用sql编写的电子邮件确认函数更改为PDO。这是您进一步参考的教程:http://www.phpeasystep.com/phptu/24.html

此特定部分会在用户点击发送到其电子邮箱的验证链接后将用户的信息从临时表移至永久表。

我遇到的问题是在该教程的标题下: STEP4:confirmation.php

我的代码与此类似,但我在尝试阻止SQL注入时添加了一些预处理语句。

要明确:我正在寻找方向,我还需要做什么来将其从sql切换到PDO并防止任何sql注入。提供答案的例子至关重要,因为我是一名视觉学习者。谢谢。

这是我的代码:

<?php

include('config.php');

//Test DB connection
try {
    $conn = new PDO("mysql:host=$Host;db=$svrDb", Username, $Password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} 
catch(PDOException $e) {
    echo 'ERROR: ', $e->getMessage(), "\n";
}

// Passkey that got from link
$passkey=$_GET['passkey'];

$sql1= $conn->prepare("SELECT * FROM temp_members_db WHERE confirm_code ='$passkey'");
$sql_conf1->execute() or die ('Error updating database: '.mysql_error());
$result1=$sql1->fetchall();

// If successfully queried
if($result1){

// Count how many row has this passkey
$count=mysql_num_rows($result1);

// if found this passkey in our database, retrieve data from table "temp_members_db"
if($count==1){

$name=$rows['name'];
$email=$rows['email'];
$password=$rows['password'];
$country=$rows['country'];

// Insert data that retrieves from "temp_members_db" into table "registered_members"
$sql2="INSERT INTO registered_members(name, email, password, country)VALUES('$name', '$email', '$password', '$country')";
$result2=mysql_query($sql2);
}

// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}

// if successfully moved data from table"temp_members_db" to table "registered_members" displays message "Your account has been activated" and don't forget to delete confirmation code from table "temp_members_db"
if($result2){

echo "Your account has been activated";

// Delete information of this user from table "temp_members_db" that has this passkey
$sql3="DELETE FROM temp_members_db WHERE confirm_code = '$passkey'";
$result3=mysql_query($sql3);

}

}
?>

1 个答案:

答案 0 :(得分:0)

好的,所以你走在正确的轨道上但不是......

使用Prepared Statements的全部原因是数据库知道要解释为SQL的内容,以及不能解释为SQL的内容。现在,您有以下内容:

$sql1= $conn->prepare("SELECT * FROM temp_members_db WHERE confirm_code ='$passkey'");
$sql_conf1->execute() or die ('Error updating database: '.mysql_error());
$result1=$sql1->fetchall();

要充分利用PDO和Prepared Statements,您应该将其更改为:

$sql1= $conn->prepare("SELECT * FROM temp_members_db WHERE confirm_code = ?");
try{
     $sql1->execute(array($passkey));
}catch(PDOException $e){
     print "Error!: " . $e->getMessage() . "<br/>";
     die();
}
$result1=$sql1->fetchall();

这有几个原因。在您的代码中,您将变量$passkey与您的prepare语句一起发送,因此实际上准备操作是无用的,因为$passkey尚未被清理。请注意,在我的代码中,我将其替换为?。这告诉数据库:

“嘿,我将执行一个SELECT语句,我将用我的一个变量中的值替换?,所以不要将其解释为SQL! “

这是PDO的一个很好的资源:

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers