尝试从表单中获取数据并使用PDO插入数据库

时间:2014-12-05 17:12:40

标签: php forms pdo

我正在尝试从表单提交数据,并使用PDO将数据插入到我的数据库中。我不确定我在这一点上做错了什么,可以使用我能得到的任何帮助。

以下是连接我的数据库的代码

<?php
function connect(){
    $config = array(
      '$username' => 'root',
      '$password' => 'root'
    );
    try {
      $conn = new PDO('mysql:host=localhost;dbname=data', $config['$username'], $config['$password']);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      echo 'COME GET SOME IT WORKED!!!!';
    }
    catch(PDOException $e) {
      print "Error!";
      exit;
    }
}

?>

以下是处理表单数据的代码

<?php
 // We will include connection file first
 include('functions.php');
 connect();
 // check if varaibable is set and Add Rate Button pressed.
if(isset($_POST["submit"])){
   echo 'COME GET SOME';
   // Define Variables
   $firstname = $_POST[firstName]; //firstName
   $lastname = $_POST[lastName]; //LastName
   $email = $_POST[emailAddress]; //Email Address
   $age = $_POST[age]; //Age

   // We Will prepare SQL Query
   $STM = $dbh->prepare("INSERT INTO 'EmailList'(id, firstName, lastName, emailAddress, age) VALUES (NULL, :firstname, :lastname, :email, :age)");
   // bind paramenters, Named parameters always start with colon(:)
      $STM->bindParam(':firstname', $firstname);
      $STM->bindParam(':lastname', $lastname);
      $STM->bindParam(':email', $email);
      $STM->bindParam(':age', $age);
   // For Executing prepared statement we will use below function
      $STM->execute();
   // We use header here for redirecting it to other page where we will show success message.                       
      header( "location:index.php");                   
   }
?> 

0 个答案:

没有答案