【问题标题】:INSERT into two different tables with a related key使用相关键插入两个不同的表
【发布时间】:2014-05-13 10:49:24
【问题描述】:

单击提交按钮后,我试图向几个相关的数据库表中插入一些数据,我的表是:

用户:ID(主键)、用户、名称、密码

LEVELS:ID、User_ID(外键)、Level1、Level2、Level3、Level4

其中表级别的 User_ID 与用户的主键 ID 相同。

我想用php做这个插入,我的代码如下:

$host="xxxxxx"; // Host name 
$username="xxxxxx"; // Mysql username 
$password="xxxxxx"; // Mysql password 
$db_name="xxxxxx"; // Database name 
$tbl_name="USERS"; // Table name 

// Connect to server and select databse.
$dbh= mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// sent from form 
$name=$_POST["name"]; 
$user=$_POST["user"];
$password=$_POST["password"]; 
$L4=$_POST["L4"]; 
$L3=$_POST["L3"];
$L2=$_POST["L2"]; 
$L1=$_POST["L1"]; 

$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$userid = mysql_insert_id();
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");

$sql2 = "INSERT INTO LEVELS (User_ID, Level1, Level2, Level3, Level4) VALUES('$userid','$L1','$L2','$L3','$L4');";
$tab2= mysql_query($sql2, $dbh) or die ("problem query 2");

要么,我不知道如何关联表,或者这里有问题,因为只执行了第一个 sql 语句,而第二个打印了 die 'problem query 2'。

谁能帮帮我?

谢谢!

【问题讨论】:

  • 您是否从第二个查询中收到特定错误?此外,您应该考虑清理输入并使用 PDO 或 Mysqli 而不是 mysql_query/mysql_*。您的代码原样存在许多潜在的安全问题。
  • 没有错误,只是我放在'or die();'的括号之间的那个
  • 您是否尝试在您的die 声明中打印出mysql_error()
  • 我不确定,但请在您的查询中尝试 `LEVELS`

标签: php mysql insert primary-key


【解决方案1】:
$userid = mysql_insert_id();

应该在执行插入查询之后调用,在您的情况下,您是在执行第一个查询之前调用它。

应该是这样的

$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$userid = mysql_insert_id();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多