[英]insert images in another table with foreign key
I have two tables in my db, telephones(id, title, price)
and images(id, tp_id, photos)
I went in the images
table and put a foreign key on the tp_id
column to match the id
in the telephones
table so that every image is linked to a telephone
. 我的数据库中有两个表, telephones(id, title, price)
和images(id, tp_id, photos)
我进入images
表并在tp_id
列上放置一个外键以匹配telephones
表中的id
,以便每张图片都与telephone
相关联。 But the problem is my images go into the table fine but the tp_id
column always has the value of 0, what I am missing here? 但问题是我的图像进入表格很好,但tp_id
列的值总是为0,我在这里缺少什么? can somebody guide me? 有人可以指导我吗? Thanks 谢谢
PS: I know about the security vulnerability of my code I am just doing some test here! PS:我知道我的代码的安全漏洞我只是在这里做一些测试!
<?php
if (isset($_POST['submit'])) {
include 'dbconnect.php';
for ($i = 0; $i < count($_FILES["photo"]["name"]); $i++) {
$target = "img/"; //This is the directory where images will be saved
$target_files = $target . basename($_FILES['photo']['name'][$i]); //This gets all the other information from the form
$ad_title = $_POST['title'];
$ad_price = $_POST['price'];
$ad_photo = $target . ($_FILES['photo']['name'][$i]);
if (!move_uploaded_file($_FILES['photo']['tmp_name'][$i], $target_files)) { //Tells you if its all ok
echo "Sorry, there was a problem uploading your file.";
} else { //Gives and error if its not
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$sql1 = "INSERT INTO images (photos) VALUES ('$ad_photo') ";
$conn->query($sql1);
//Writes the photo to the server
header('location: addconfirm.php');
}
}
}
?>
使用此获取最后插入的主键值
$last_id = $conn->insert_id;
You need to get last insert id form telephones
table using $conn->insert_id;
您需要使用$conn->insert_id;
获取最后一个插入id表格telephones
表$conn->insert_id;
and the insert into images
table as 并插入到images
表中
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_id=$conn->insert_id;// get last insert id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_id) ";
$conn->query($sql1);
Note:- Your script is Open for sql injection check How can I prevent SQL injection in PHP? 注意: - 您的脚本是打开以进行SQL注入检查如何在PHP中阻止SQL注入? to prevent it 防止它
Question has already been answered many times Use : MySQL: LAST_INSERT_ID() 问题已经多次回答使用:MySQL:LAST_INSERT_ID()
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_last_insert_id = $conn->LAST_INSERT_ID;// get last insert id
you should call this function right after you insert to get the latest added id 您应该在插入后立即调用此函数以获取最新添加的ID
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_last_insert_id) ";
$conn->query($sql1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.