无法用php将数据插入mysql数据库

时间:2014-07-10 21:12:07

标签: php mysql insert

我无法通过PHP将数据插入到我的表中。 " cc_connect.php"是连接数据库的文件。表单在那里但是当我提交它时,没有数据添加到我的表中。我已经按照几个教程进行了匹配,并且没有成功。我的数据库中没有设置某些内容吗?

函数$ dbcon与我的连接

相关联
<form method="post" action="cc_registration.php">
<input type="hidden" name="submitted" value="true" />

    First Name: <input type="text" name="first_name" />
    Last Name: <input type="text" name="last_name" />

<br />
<input type="submit" value="submit" />

  <?php

   if(isset($_POST['submit'])) {

   include ('cc_connect.php');

   if (!$dbcon) {

   die("Can not Connect: " . mysql_error());

}

   mysql_select_db("cooperstown",$dbcon);

$sql = "INSERT INTO cobra_registration (first_name,last_name) VALUES ('$_POST[first_name]', '$_POST[last_name]')";

mysql_query($sql,$dbcon);



mysql_close($dbcon);

}

  ?>

2 个答案:

答案 0 :(得分:3)

$_POST['submit']永远不会设置,因为您正在传递submitted

变化:

<input type="hidden" name="submitted" value="true" />

为:

<input type="hidden" name="submit" value="true" />

作为旁注,您当前的查询很容易被黑客入侵。使用Prepared语句代替PDO或MysQLi,这是PDO中的一个例子:

$fName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lName = isset($_POST['last_name']) ? $_POST['last_name'] : '';

if ($fName && $lName) {
   $stmt = $db->prepare('
      INSERT INTO cobra_registration (first_name,last_name) 
      VALUES (:fname, :lname)
   ');

   $stmt->bindParam(':fname', $fName, PDO::PARAM_STR);
   $stmt->bindParam(':lname', $lName, PDO::PARAM_STR);

   $res = $stmt->execute();

   if ($res) {
      echo 'Success';
   } else {
      echo 'Failure';
   }
}

答案 1 :(得分:2)

不推荐使用mysql_ *函数,不应再使用它们。查看mysqliPDO

重要提示

这对SQL Injection attacks开放。您应该使用准备好的语句来防止此类攻击。

GGio确认了他的答案,那是submitted,但检查submit。他还提供了一个PDO示例,因此我将在mysqli中演示相同的内容:

$firstName = isset($_POST['first_name']) ? $_POST['first_name'] : '';
$lastName = isset($_POST['last_name']) ? $_POST['last_name'] : '';

if ($firstName && $lastName) {
    $stmt = $mysqli->prepare("INSERT INTO cobra_registration (first_name,last_name) 
  VALUES (?, ?)"); 
    $stmt->bind_param("ss", $firstName, $lastName);
    $stmt->execute();  

}
相关问题