我正在尝试学习如何使用PDO,这样我的表单就不会被SQL注入。
我对如何为我的insert编写execute函数感到困惑。
这是我的代码:
$db = new PDO('mysql:host=x;dbname=x;charset=utf8', 'x', 'x');
if ( !$db )
{
die('Could not connect: ' . mysql_error());
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$mail = $_POST['mail'];
$stmt = $db->prepare("SELECT * FROM ucm_signup WHERE email =? ") or exit(mysql_error());
$stmt->bindValue(1, $mail, PDO::PARAM_STR);
$stmt->execute();
$num_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($num_rows == 0)
{
//if there are no duplicates...insert
$sql = $db->prepare("INSERT INTO ucm_signup company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress )
VALUES ( '$_POST[company]','$_POST[address1]','$_POST[address2]','$_POST[city]', '$_POST[province]','$_POST[zip]','$_POST[fname]','$_POST[lname]','$_POST[mail]', '$_POST[phone]','$_POST[session]','$_POST[iama]','$_POST[buyfrom]','$_POST[group1]', '$ipaddress')");
$sql->execute(array(':company' => I AM LOST))
}
我是不是已经接近插页了?谢谢你
最佳答案
您应该检查rowCount()
,而不是获取行并检查是否为零。您的第一个查询是正确的,但是第二个查询需要更改,您还需要在这里使用prepared语句并绑定参数,例如
$num_rows = $stmt->rowCount();
if($num_rows == 0)
{
$sql = $db->prepare("INSERT INTO ucm_signup company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress )
VALUES (:company,:address1,:address2, .....)");
$sql->bindParam(':company',$_POST[company],PDO::PARAM_STR);
$sql->bindParam(':address1',$_POST[address1],PDO::PARAM_STR);
$sql->bindParam(':address2',$_POST[address2],PDO::PARAM_STR);
//and so on
$sql->execute();
}
关于php - 使用PDO的PHP sql,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22541876/