gpt4 book ai didi

php - 如何将父表当前主键的值插入到子表中

转载 作者:行者123 更新时间:2023-11-29 08:09:24 24 4
gpt4 key购买 nike

我有两个表employee表(父表)和employee_image表(子表)。

employee表(employee_id为本父表自增主键)

|=============================|
|employee_id employee_name |
| 1 ram |
| 2 sham |
| 3 dany |
| 4 james |
|=============================|

employee_image 表(插入值表后应如下所示)

|=====================================================|
|image_id name image employee_id |
| 1 img_one [BLOB-22.3KiB] 2 |
| 2 img_two [BLOB-24.5KiB] 3 |
| 3 img_three [BLOB-32.2KiB] 3 |
| 4 img_four [BLOB-18.6KiB] 3 |
| 5 img_five [BLOB-17.7KiB] 4 |
|=====================================================|

在第一个 insert.php 表单中,我使用此脚本

<html>
<head>
<title>
</title>
</head>
<body>
<form action="commit.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>employee name : </td><td><input type ="text" name ="employee_name"/></td></tr>
<tr><td>upload image 1 : </td><td><input type="file" name="image"></td></tr>
<tr><td>upload image 2 : </td><td><input type="file" name="image"></td></tr>
<tr><td>upload image 3 : </td><td><input type="file" name="image"></td></tr>
<tr><td><input type ="submit" name="submit" value ="submit"/></td></tr>
</table>
</body>
</html>

在第二页“commit.php”中我正在使用这个脚本

<?php
$db=mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection paramerters.');

mysql_select_db('my_db', $db) or die(mysql_error($db));


$query ='INSERT INTO employee_tbl
(employee_name)
VALUES
("' . $_POST['employee_name'] . '")';
mysql_query($query, $db) or die(mysql_error($db));
echo 'employee name inserted succecfully!';

$imageName=mysql_real_escape_string($_FILES["image"]["name"]);
$imageData=mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType=mysql_real_escape_string($_FILES["image"]["type"]);

if(substr($imageType,0,5) == "image")
{
mysql_query("insert into test_image values ('', '$imageName', '$imageData')");
echo "image uploaded";
}
else
{
echo "only images are allowed";
}
}
?>

这里employee_id是employee表(父表)中的主键。我想同时插入一张或两张或三张图像。我的目标是将当前插入的employee_id也插入到employee_image表(子表)中...我该怎么做?谢谢你帮助我。

最佳答案

替换这个

mysql_query("insert into test_image values ('', '$imageName', '$imageData')");

与:

$id = mysql_insert_id();
mysql_query("insert into test_image values ('', '$imageName', '$imageData','$id')");

关于php - 如何将父表当前主键的值插入到子表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com