<?php
include 'connection.php';
session_start();
$noteinfo = array();
$noteinfo['note'] = $_POST['note'];
$_SESSION['noteinfo'] = $noteinfo;
if (isset($_POST['submit'])) {
if (empty($_POST['note'])) {
echo "Dobavete Komentar";
}
if (!empty($_SESSION['noteinfo'])) {
$check = mysqli_escape_string($conn,$_SESSION['userinfo']['fname']);
print_r($_SESSION['userinfo']);
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id)
SELECT users.user_id,addresses.address_id
FROM ( VALUES () )";
if (mysqli_query($conn,$sql)) {
echo "Added";
if (mysqli_query($conn,$sql1)) {
echo "Added";
if (mysqli_query($conn,$sql2)) {
echo "Added";
if (mysqli_query($conn,$sql3)) {
echo "Mai stana toq put";
header("refresh:3 ; url=profile.php");
}
}
}
}
else{
echo "Error";
}
}
else{
header("refresh:1 ; url=zapiski.php");
}
}
?>
我的问题是针对$ sql3:我想在表单填写完毕后用用户ID和地址表中的ID填充users_addresses,但是现在SQL并没有在表users_addresses中填充任何内容。这些是我的表格:
答案 0 :(得分:0)
当用户在应用程序中填写值并且您需要为它们查找id时,编写查询的典型方法如下所示:
INSERT INTO users_addresses (ua_user_id, ua_address_id)
VALUES ( (SELECT u.user_id FROM users u WHERE u.username = ?),
(SELECT a.address_id FROM address a WHERE a.address = ?)
);
也就是说,您要将参数传递到查询中,使用参数查找ID,然后使用这些ID插入联结表。
答案 1 :(得分:0)
您似乎在VALUES()
中缺少INSERT
函数。
INSERT INTO users_addresses(ua_user_id,ua_address_id)
应该是
INSERT INTO users_addresses(ua_user_id,ua_address_id) VALUES(some_variable,some_variable)
您也可以这样做
INSERT INTO users_addresses SET ua_user_id=some_variable, ua_address_id=some_variable
在选择数据时,您需要JOIN
表。我建议在此问题上使用LEFT JOIN
。重要的是,您要在JOIN
中相互匹配的id是一致的,以便能够将表链接在一起。然后,如果要解析user_id(即WHERE
子句),则由您决定是否要满足特定条件。
选择特定匹配项的示例:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
WHERE
users_addresses.ua_id = $some_id
选择所有匹配项的示例:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
让我知道这是否是您想要的,以及是否需要详细说明。
一个重要的注意事项,因为您正在使用mysqli_ *扩展名,所以应该研究准备好的语句。由于您现在可以使用SQL注入,因此它将大大提高安全性。