如何在两个不同的表的两行中插入相同的UUID

时间:2012-08-29 10:04:29

标签: php mysql database uuid

我尝试下一个脚本:

// Insert data into mysql 

$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES (UUID(), '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry);

$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$ID')"; <--- Here is a problem
$result=mysql_query($qry2)

我不知道两个表格如何在两个表格中插入相同的UUID 。请帮我! 我非常感谢你的支持!

DONE !!! 工作脚本:

$q = "SELECT UUID() AS uid";
$res = mysql_query($q) or die('q error: '.mysql_error());
$row = mysql_fetch_assoc($res);

// Insert data into mysql 
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('".$row['uid']."', '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry) or die('err 034r '.mysql_error());

$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('".$row['uid']."')";
$result=mysql_query($qry2) or die('gg2345  '.mysql_error());

2 个答案:

答案 0 :(得分:2)

在发送SELECT UUID()之前,只需执行INSERT并将值放入PHP中的语句中。像这样(未经测试):

$result = mysql_query("SELECT UUID() AS UUID") or die('SQL error: ' . mysql_error());
$row = mysql_fetch_assoc($result);
$UUID = $row["UUID"];

$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('$UUID', '$REFERENCE',   '$CODE', '$NAME')";
$result=mysql_query($qry);

$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$UUID ')"; <--- Here is a problem
$result=mysql_query($qry2)

另一种方法是使用用户定义的变量(see SQL Fiddle):

SET @UUID = (SELECT UUID() AS UUID);
INSERT INTO test1 VALUES(@UUID, "foo");
INSERT INTO test1 VALUES(@UUID, "bar");

答案 1 :(得分:1)

假设ID是您可以在$qry2之前添加的表唯一索引:

$ID = mysql_insert_id();