我正在尝试插入艺术家、歌曲和唱片公司的记录,同时检查数据是否已存在于数据库中。
以下代码来自Mike Fenwick .
<?php
$query = "SELECT id FROM table WHERE unique1=value1 AND unique2=value2…";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET unique1=value1 AND unique2=value2…";
$insert_result = mysql_query($query);
$id = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$id = $row['id'];
}
return $id;
?>
我需要修改它以检查是否已经存在三个唯一值(来自 3 个单独的表),如果不存在,则插入它们。这是我的尝试:
<?php
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysql_query($query);
$artistID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$artistID = $row['artistID'];
}
return $artistID;
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysql_query($query);
$labelID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$labelID = $row['labelID'];
}
return $labelID;
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$songID = $row['songID'];
}
return $songID;
?>
我假设一定有更有效的方法来做到这一点。任何想法将不胜感激。
最佳答案
使用基本的插入/忽略语法你可以做这样的事情。
插入艺术家详细信息和标签详细信息的几个插入,然后是基于 SELECT 的插入:-
<?php
$query = "INSERT IGNORE INTO artistTable (artistName, artistImag) VALUES('Beyonce', 'beyonce.jpg')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO labelTable (labelName) VALUES('Columbia Records')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO songTable (trackTitle, artistID, labelID)
SELECT 'Crazy in Love', a.artistID, b.labelID
FROM artistTable a
INNER JOIN labelTable b
ON a.artistName = 'Beyonce'
AND a.artistImag = 'beyonce.jpg'
AND b.labelName = 'Columbia Records'";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
return $songID;
?>
正如@LoganWayne 所说,您可能应该使用 MySQLi。
关于php - 如何为多行修改此 MySQL INSERT 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116658/