我有3张桌子:
用户 - uID(INT AUTO_INCREMENT),名称(VARCHAR)
电影 - mID(IN AUTO_INCREMENT),标题(VARCHAR)
观看 - uID(INT),mID(INT)
我正在编写一个php函数,它构造一个查询,添加特定人观看的电影记录。这是我到目前为止所提出的:
function set_watched($name, $movies){
$sql = "SET @userid = (SELECT uID FROM users WHERE name = '$name' LIMIT 1); ";
$sql .= "INSERT INTO watched (uID, mID) VALUES ('";
foreach ($movies as $index => $movie){
}
}
我的问题:
有没有办法将@userid变量与SELECT mID FROM MOVIES WHERE title = $movie OR title = $movie [generated with foreach]
?
我不想为每个电影标题生成单独的SELECT语句。也许我根本不需要使用@userid变量?
答案 0 :(得分:2)
尝试这样的事情:
$sql = "INSERT INTO watched (uID, mID)
SELECT User.uID, Movies.mID
FROM (SELECT uID FROM Users WHERE Users.name = '$name' LIMIT 1) AS User, Movies
WHERE ";
foreach ($movies as $index => $movie){
$sql .= "Movies.title = '$movie' OR ";
}
$sql = substr($sql, 0, -4) . ";";
答案 1 :(得分:1)
我更喜欢使用数组并将它们插入到这种应用程序中。此外,我不会尝试将这两件事强制一个查询。我要么:
uID
作为其输入,而不是name
此外,PHP的mysql_query函数不支持多个查询,因此如果您使用的是标准的mysql函数,则只需调用一次mysql_query即可执行两个查询。
使用案例#2运行,您可以使用类似的东西(当然未经测试):
$sql = 'SELECT uID FROM users WHERE name = "' . $name. '" LIMIT 1';
$result = mysql_query( $sql);
$row = mysql_fetch_row( $result);
mysql_free_result( $result);
$values_array = array();
foreach ($movies as $index => $movie)
{
$values_array[] = '( "' . $row['uID'] . '", "' . $movie . '")';
}
$sql = 'INSERT INTO watched (uID, mID) VALUES ' . implode( ', ', $values_array);
$result = mysql_query( $sql);