php - 从一种表单插入多个表(mysql 和 PHP)

标签 php mysql insert transactions

我是这个网站和编码的新手,所以如果您遇到一些菜鸟错误,请对我宽容一点。

我有一个表单,提交后会将数据插入两个单独的表(users、users_addresses)。用户地址应通过用户 ID 链接回用户。

我已经看到了几种不同的方法可以用于解决此类问题(但没有一种 IC 可以工作),但我正在寻求帮助,看看哪一种是最好的方法。

这是我到目前为止所拥有的:

public function createNewUser($details, $active) 
{
    $password  = $details["password"];
    $username  = strtolower($details["username" ]);
    $firstname = strtolower($details["firstname"]);
    $lastname  = strtolower($details["lastname" ]);
    $email     = strtolower($details["email"    ]);
    $sex       = strtolower($details["sex"      ]);
    $datepicker  = strtolower($details["datepicker" ]);
    $disabled  = ($active) ? "0" : "1";
    $address1     = strtolower($details["address1"    ]);
    $address2     = strtolower($details["address2"    ]);
    $province     = strtolower($details["province"    ]);
    $city     = strtolower($details["city"    ]);
    $district     = strtolower($details["district"    ]);
    $zipcode     = strtolower($details["zipcode"    ]);


    $

    $sql       = "INSERT INTO users VALUES (NULL, LOWER('$username'), MD5('$password'), LOWER('$firstname'), LOWER('$lastname'), LOWER('$email'), LOWER('$sex'), LOWER('$datepicker'), 0, NOW(), $disabled, 0)";

    $resultSet = $this->db->query($sql);
    return $this->db->getInsertId();

    $sql      = "INSERT INTO users_addresses VALUES (NULL, LOWER('$userid'), LOWER('$address1'), LOWER('$address2'), LOWER('$province'), LOWER('$city'), LOWER('$district), LOWER('$zipcode')";
    $resultSet = $this->db->query($sql);
    return $this->db->getInsertId();
 }

最佳答案

第二个查询永远不会执行,因为在所有条件下执行之前都有一个 return 语句。即使已更正,第二个查询中的 $user_id 尚未填充从第一个查询中获得的值。解决方案如下:

第一

return $this->db->getInsertId();

应替换为

$user_id=$this->db->getInsertId();

第二

return $this->db->getInsertId();

应替换为

return $user_id

关于php - 从一种表单插入多个表(mysql 和 PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400700/

相关文章:

Java插入具有自动增量字段的表

php - 无法连接并写入mysql数据库

php - fatal error : Maximum execution time of 30 seconds exceeded

mysql - 删除重复的字符串列表

php - 在 MySql 中连接表来存储已查看的文章 ID

mysql - 选择 SUM 大于 X 的行

r - 根据列条目插入行,并根据插入的位置确定插入行的条目

php - 从一年的开始日期开始计算假期天数,然后每年计算

php - 尽管使用 PDO::PARAM_INT 参数,MySQL/PDO::quote() 还是在整数周围加上引号

php - 插入MYSQl太慢