我是PHP的新手,我正在尝试通过表单输入联系人详细信息。我将以下代码放在一起从表单中获取信息并将其存储到数据库中。此代码基于几个教程。第一个代码工作,但我不确定这里的安全/ SQL注入。第二种方法是PDO方法。我没有收到任何错误消息,但表没有更新。哪种方法最好,以及为什么没有插入PDO的任何指针。表格
<form action="contactForm.php" method="post">
<p>Name: <input name="name" type="text" id="name" size="60"></p>
<p>Email address: <input name="email" type="email" id="email" size="40"></p>
<p>Phone: <input name="phone" type="tel" id="phone" size="40"></p>
<p>Twitter: <input name="twitter" type="text" id="twitter" size="40"></p>
<p>Comment:</p>
<p><textarea name="comment" cols="55" rows="5"id="comment"></textarea></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
第一种方法
if(isset($_POST['submit'])){
define('DB_NAME','users');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','localhost');
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$conn){
die('Sorry, we could not connect at this time:'.mysql_error());
}
$db_selected=mysql_select_db(DB_NAME, $conn);
if(!$db_selected){
die('Cannot use'.DB_NAME.':'.mysql_error());
}
mysql_select_db("users", $conn);
$sql = "INSERT INTO usercontacts (name, email, phone, twitter, comment) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[phone]', '$_POST[twitter]', '$_POST[comment]')";
mysql_query($sql,$conn);
mysql_close($conn);
}
和PDO方法
$dbname = 'users';
$dbuser = 'root';
$dbpassword = '';
$dbhost = 'localhost';
try{
$db = new PDO('mysql:host='.$dbhost.';dbname'.$dbname,$dbuser, $dbpassword);
}
catch(PDOException $e){
echo $e->getMessage();
}
if(isset($_POST['name'])){
$name= $_POST['name'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$twitter= $_POST['twitter'];
$comment= $_POST['comment'];
$query = $db->prepare("INSERT INTO usercontacts (name, email, phone, twitter, comment) VALUES (:name, :email, :phone, :twitter, :comment)");
$query->bindValue(':name',$name);
$query->bindValue(':email',$email);
$query->bindValue(':phone',$phone);
$query->bindValue(':twitter',$twitter);
$query->bindValue(':comment',$comment);
$query->execute();
}
答案 0 :(得分:1)
这里有一个错误:
$db = new PDO('mysql:host='.$dbhost.';dbname'.$dbname,$dbuser, $dbpassword);
它应该是:
$db = new PDO('mysql:host='.$dbhost.';port=3306; dbname='.$dbname, $dbuser, $dbpassword);