从单个表单将数据插入多个SQL表

时间:2016-05-19 06:47:17

标签: php mysql

嘿..我在PHP代码上有点困难,无法将数据插入到多个SQL表中。我无法在单个操作中将数据导入两个表。这是一个注册页面,用于创建用户登录和公司简介的开始。任何建议将不胜感激。感谢

  <?php
session_start();
if(isset($_SESSION['user'])!="")
{
    header("Location: home.php");
}
include_once 'resources/php/dbconnect.php';




if(isset($_POST['btn-signup']))
{
    $uname = mysql_real_escape_string($_POST['uname']);
    $email = mysql_real_escape_string($_POST['email']);
    $upass = md5(mysql_real_escape_string($_POST['pass']));
    $orgname = mysql_real_escape_string($_POST['orgname']);

    $uname = trim($uname);
    $email = trim($email);
    $upass = trim($upass);
    $orgname = trim($orgname);

    // email exist or not
    $query = "SELECT user_email FROM users WHERE user_email='$email'";
    $result = mysql_query($query);

    $count = mysql_num_rows($result); // if email not found then register

    if($count == 0){

        if(mysql_query("START TRANSACTION; 
        INSERT INTO users('user_name','user_email','user_pass') 
            VALUES('$uname','$email','$upass');
        INSERT INTO companies('name','owner_id') 
            VALUES('$orgname','$email');
        END;"))
        {
            ?>
            <script>alert('Registration Successful');</script>
            <?php
        }
        else
        {
            ?>
            <script>alert('error while registering you...');</script>
            <?php
        }       
    }
    else{
            ?>
            <script>alert('Sorry Email ID already taken ...');</script>
            <?php
    }

}

?>

2 个答案:

答案 0 :(得分:0)

你可以这样做两个插页:

$queryUsers = INSERT INTO users('user_name','user_email','user_pass') 
            VALUES('$uname','$email','$upass');
mysql_query($queryUsers);
$queryCompanies = INSERT INTO companies('name','owner_id') 
            VALUES('$orgname','$email');
mysql_query($queryCompanies);

另外,小心使用mysql_query,不推荐使用,请尝试使用mysqli()。 此致

答案 1 :(得分:0)

正如您所见,here已弃用mysql扩展名,而您必须停止使用它。很好的选择是PDOmysqli

您还应该使用Prepared Statements来保护您的代码免受SQL注入攻击。

要使用PDO完成交易,您可以执行以下操作:

$conn->query("START TRANSACTION");
$stmt = $conn->prepare("INSERT INTO users(user_name,user_email,user_pass) VALUES(?,?,?)");
try
{
    $stmt->bindValue(1,$user_name);
    $stmt->bindValue(1, $user_email);
    $stmt->bindValue(3, $user_pass);
    $stmt->execute();
    $secondStmt = $conn->prepare("INSERT INTO companies(name,owner_id) VALUES(?,?)");
    $secondStmt->bindValue(1, $name);
    $secondStmt->bindValue(2, $owner_id);
    $secondStmt->execute();
    $conn->query("COMMIT");   //This commits all changes if no error occured
}
catch(Exception $e)
{
    $conn->query("ROLLBACK");  //This reverts any changes made in case of an error
}