如何在数据库中插入记录

时间:2016-07-13 09:32:09

标签: php mysql

我正在尝试将表单中的记录插入到数据库中,但在单击“提交”后,它会显示“您的SQL语法中有错误;请查看与您的MySQL服务器版本对应的手册以获得正确的语法”错误.... 请帮帮我

<?php
include('data_conn.php');

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

  $email = mysql_real_escape_string( $_POST['email']);
$query = "SELECT * FROM login WHERE email='$email'";
    $result = mysql_query($query) or die(mysql_error());

    if (mysql_num_rows($result) ) {
        echo '<script language="javascript">';
    echo 'alert("Email is Already Exist...."); location.href="signup.php"';
    echo '</script>';
    }
    else {
        $f_name = $_POST['f_name'];

        $c_name = $_POST['c_name'];
        $c_add = $_POST['c_add'];
        $mob = $_POST['mob'];
        $email = $_POST['email'];
        $password = $_POST['password'];



        $query = "INSERT INTO login (first_name,company_name,company_add,mob,email,password) VALUES ('$f_name,'$c_name','$c_add','$mob','$email','$password')";


       $result = mysql_query($query) or die(mysql_error());


       if($result==1)
    {
        echo '<script language="javascript">';
    echo 'alert("successfully registered!!!"); location.href="signup.php"';
    echo '</script>';
    }
    else
    {
      echo '<script language="javascript">';
    echo 'alert("Something Went Wrong!!! :("); location.href="signup.php"';
    echo '</script>';
    }
    }
}
?>

3 个答案:

答案 0 :(得分:1)

更改以下行

$query = "INSERT INTO login (first_name,company_name,company_add,mob,email,password) VALUES ('$f_name,'$c_name','$c_add','$mob','$email','$password')";

到此

$query = "INSERT INTO login (first_name,company_name,company_add,mob,email,password) VALUES ('$f_name','$c_name','$c_add','$mob','$email','$password')";

问题是,您只向变量'添加了一个$f_name。只需将其设为'$f_name'即可使用

答案 1 :(得分:0)

您可以使用以下方法来避免使用直接替换值,而不是使用直接替换值。

你基本上有两个选择来实现这个目标:

1)使用PDO(对于任何支持的数据库驱动程序):

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

2)使用MySQLi(用于MySQL):

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

请参阅How can I prevent SQL injection in PHP?

答案 2 :(得分:0)

语法错误。
尝试:

$query = "INSERT INTO login (first_name,company_name,company_add,mob,email,password) VALUES ('$f_name','$c_name','$c_add','$mob','$email','$password')";

而不是:

$query = "INSERT INTO login (first_name,company_name,company_add,mob,email,password) VALUES ('$f_name,'$c_name','$c_add','$mob','$email','$password')";

'$f_name'中缺少单引号。