PHP函数没有将数据传递给MySQL

时间:2015-12-16 06:34:00

标签: php mysql

我已经设置了一个注册页面来注册用户,它从HTML传递到PHP 但是PHP函数没有将它传递给MySQL数据库

   <?php
     try{
      $db = new PDO ("mysql:host=localhost;dbname=car_rental;port=3306","root","");

    }
    catch (Exception $e){
      echo "SQL is Off";
      exit;

    }
    echo "success"; 

    try{
    $trial = "INSERT INTO users (firstName) VALUES ('trial')";

    }
    catch (Exception $e){
      echo "doesnt work..";
    }
    echo "works?";
     try{
     function NewUser() 
     { 
       $firstName = $_POST['firstName'];
       $lastName = $_POST['lastName'];
       $age = $_POST['age'];
       $email = $_POST['email']; 
      $password = $_POST['pass']; 
      $query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
      echo"user created";
      }
     }
     catch (PDOException $e)
     {
       echo "ERROR -_-";
     }

      ?>

这是在PHP中执行sql查询的正确实现吗?

function NewUser() 
 { 
   $firstName = $_POST['firstName'];
   $lastName = $_POST['lastName'];
   $age = $_POST['age'];
   $email = $_POST['email']; 
  $password = $_POST['pass']; 
  $query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
  $db->exec($query);
  echo"user created";
  }

由于

1 个答案:

答案 0 :(得分:2)

您只需编写查询,但忘记执行

$db = new PDO ("mysql:host=localhost;dbname=car_rental;port=3306","root","");
$query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
$db->query($db); // executes it