【问题标题】:Insert into multiple tables from one form (mysql and PHP)从一种形式插入多个表(mysql和PHP)
【发布时间】:2013-08-23 10:35:37
【问题描述】:

我是这个网站和编码的新手,所以如果你遇到一些菜鸟错误,请放轻松。

我有一个表单,提交时会将数据插入两个单独的表(用户、用户地址)。用户地址应通过用户 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();
 }

【问题讨论】:

  • 您非常想将值设为小写。您首先在 PHP 中使用 strtolower,然后在 MySQL 查询中使用 LOWER()。奇怪。
  • 越低越好哈哈:D

标签: php mysql insert transactions


【解决方案1】:

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

第一

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

应该替换为

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

第二

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

应该替换为

return $user_id

【讨论】:

    【解决方案2】:

    您的代码有很多错误/奇怪的地方:

    1. 不要将变量直接放在 SQL 代码中,而是使用prepared statements
    2. 您正在对所有数据调用strtolowerLOWER。无需重复。
    3. 第二个查询永远不会完成,因为你在它之前return。那是“无法访问的代码”。

    修复可能通过将第一个 return $this->db->getInsertId() 替换为 $userid = $this->db->getInsertId() 并将第二个替换为 return $userid 来完成。

    祝你好运,欢迎来到 SO。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-05
      • 2011-05-21
      • 2017-07-26
      • 2011-09-07
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多