如何在值为变量的表中插入新行?

时间:2016-02-23 13:48:44

标签: php mysql

我正在尝试使用变量INSERT将新行添加到表中,如下所示 -

$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$gender = $_POST['gender'];
if($name && $surname && $email && $password){
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $db = '_erica';
    $conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    };

    $sql = 'INSERT INTO login(id, name, surname, email, sex, password) VALUES (Null,$name,$surname,$email,$gender,$password)';

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    }else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

}else{
    die('All fields requiret!');
}; 

但是它不起作用,我试图在像这样的变量中添加引号

 $sql = 'INSERT INTO login(id, name, surname, email, sex, password) VALUES(Null,"$name","$surname","$email","$gender","$password")';

仍然没有...我该怎么办?

2 个答案:

答案 0 :(得分:1)

试试这个,

$sql = 'INSERT INTO login(id, name, surname, email, sex, password) VALUES(NULL,"'.$name.'","'.$surname.'","'.$email.'","'.$gender.'","'.$password.'")';

或(使用双引号而不是单引号)

$sql = "INSERT INTO login(id, name, surname, email, sex, password) VALUES(NULL,$name,$surname,$email,$gender,$password)";

答案 1 :(得分:1)

使用它。只需更改带双引号的单引号

$sql = "INSERT INTO login(id, name, surname, email, sex, password) VALUES (Null,$name,$surname,$email,$gender,$password)";