Php 分解后函数无法将所有行插入mysql
我有三张桌子: 用户:Php 分解后函数无法将所有行插入mysql,php,mysql,Php,Mysql,我有三张桌子: 用户: user_id (int, auto increment, primary key) username (varchar (100)) (the rest is not immportant) team_id int, user_id int, primary key (team_id, user_id), foreign key (team_id) references teams (team_id), foreign key (user_id) reference
user_id (int, auto increment, primary key)
username (varchar (100))
(the rest is not immportant)
team_id int,
user_id int,
primary key (team_id, user_id),
foreign key (team_id) references teams (team_id),
foreign key (user_id) references users (user_id)
团队:
team_id(int, auto increment, primary key)
teamname (varchar (100))
(the rest is not important)
团队用户:
user_id (int, auto increment, primary key)
username (varchar (100))
(the rest is not immportant)
team_id int,
user_id int,
primary key (team_id, user_id),
foreign key (team_id) references teams (team_id),
foreign key (user_id) references users (user_id)
我有一个表单,用户可以在其中创建一个团队,还可以添加成员名称,这些名称将是逗号分隔的值
我想要的是将团队详细信息插入到团队表和成员名称中,在使用explode并在users表中找到匹配的用户id后,将其与上次创建的团队id一起插入到团队用户中
到目前为止,我得到的是:
<?php
session_start();
$conn = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
if (!$conn) {
die("connection failed: ".mysqli_connect_error());
}
$teamname = $_POST['teamname'];
$members = $_POST['members'];
$games = $_POST['games'];
$image = $_POST['image'];
$sql = mysqli_query($conn,"INSERT INTO teams (teamname, games, images, founded) VALUES ('$teamname', '$games', '$image', NOW())");
$id = mysqli_insert_id($conn);
if(!empty($id)) {
$membernames = explode(',', $members);
foreach($membernames as $value) {
$sql = mysqli_query($conn,"insert into team_users (team_id, user_id)
select teams.team_id, users.user_id
from teams, users where users.username = '$value' and teams.team_id = '$id'");
}
if(false === $sql) die(mysqli_error($conn));
}
?>
尝试将其添加为foreach
循环中的第一行
$value=修剪($value)代码>
这是因为,当您分解逗号分隔的字符串时,很可能会在其中添加空格
例如,当我们写一个逗号分隔的字符串时,请注意每个逗号后面的空格。因此,当用逗号分解时,数组将有Adam
,Eve
,William
因此,在您的查询中,只有Adam
有效,因为Eve
和William
在开头添加了一个空格
修剪时,空间将被删除。希望这能解释。发布['members']
的价值是什么?还可以粘贴HTML吗?尝试将其添加为foreach
循环中的第一行<代码>$value=修剪($value)代码>它工作得很好!你救了我一天,非常感谢你!你能解释一下原因吗?我认为trim是用来删除空白和其他预定义字符的。修剪对这种情况有什么帮助?是的,现在一切都清楚了。谢谢你的解释!