我似乎在问一个简单的问题,但我找不到适合我的答案。我希望你能帮忙!
我正在编写一个php脚本,它从html文件(name, artist, song)
中获取一些表单数据,并将其放入带有(name, artist, song, queue, newcomer)
列的表中。现在,列newcomer
是一个布尔值;如果传入表单数据的名称值是唯一的,我希望此布尔值从默认值false或0更改为true或1。
这是我的尝试:
$newcomer = mysql_query(
'IF NOT EXISTS (SELECT DISTINCT name FROM tbl_queue)
THEN UPDATE tbl_queue newcomer=1'
);
但显然,它不起作用......
提前致谢!!
嗨,谢谢你的回答!它仍然不适合我=( 这是来自php的代码:
$ newcomer = mysql_query(“UPDATE tbl_queue SET newcomer = 1 WHERE name ='”。$ _POST [name]。“'AND NOT EXISTS(SELECT DISTINCT name FROM tbl_queue WHERE name ='”。$ _POST [name]。 “')”);
答案 0 :(得分:1)
"UPDATE tbl_queue SET newcomer=1
WHERE name = '" . $name_variable . "' AND
NOT EXISTS (SELECT DISTINCT name
FROM tbl_queue
WHERE name='" . $name_variable . "')"
这是你想要做的吗?显然用正确的变量替换$ name_variable。
编辑:重新格式化SQL
答案 1 :(得分:0)
我很想做你的初始插入: -
INSERT INTO tbl_queue (name, artist, song, queue, newcomer)
SELECT DISTINCT a.name, a.artist, a.song, a.queue, CASE WHEN b.newcomer IS NULL THEN 0 ELSE 1 END as newcomer
FROM (SELECT '$name' AS name, '$artist' AS artist, '$song' AS song, '$queue' AS queue) a
LEFT OUTER JOIN tbl_queue b
ON a.name = b.name
虚拟选择要插入的值,并根据名称对现有表进行左连接,使用CASE语句检查是否找到匹配的行。
编辑 - 下面是一些显示var赋值和转义值的php。我在你的原帖中使用了mysql_函数,但是真的应该使用mysqli_函数来进行未来验证。
<?php
$name = mysql_real_escape_string($_POST['name']);
$artist = mysql_real_escape_string($_POST['artist']);
$song = mysql_real_escape_string($_POST['song']);
$fcfs_queue = mysql_real_escape_string($_POST['fcfs_queue']);
$sql = ("INSERT INTO tbl_queue (name, artist, song, fcfs_queue, newcomer)
SELECT DISTINCT a.name, a.artist, a.song, a.fcfs_queue, CASE WHEN b.newcomer IS NULL THEN 0 ELSE 1 END as newcomer
FROM (SELECT '$name' AS name, '$artist' AS artist, '$song' AS song, '$fcfs_queue' AS fcfs_queue) a
LEFT OUTER JOIN tbl_queue b
ON a.name = b.name");
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "success";
?>
答案 2 :(得分:0)
我希望这是对Kickstart的评论,但它不符合评论的限制,所以..我希望我可以在这里回答吗?
谢谢!然而,这也不起作用...... 它返回此错误: 警告:mysql_error()期望参数1是资源(关于这一行:die('Error:'。mysql_error($ sql));在if语句中)
我的代码是:
$sql = ("INSERT INTO tbl_queue (name, artist, song, fcfs_queue, newcomer)
SELECT DISTINCT a.name, a.artist, a.song, a.fcfs_queue, CASE WHEN b.newcomer IS NULL THEN 0 ELSE 1 END as newcomer
FROM SELECT '$name' AS name, '$artist' AS artist, '$song' AS song, '$fcfs_queue' AS fcfs_queue) a
LEFT OUTER JOIN tbl_queue b
ON a.name = b.name");
if (!mysql_query($sql))
{
die('Error: ' . mysql_error($sql));
}
echo "success";
答案 3 :(得分:0)
我会使用触发器,因为它是您表的“固定”要求:
DROP TRIGGER IF EXISTS `newComerCheck`//
CREATE TRIGGER `newComerCheck` BEFORE INSERT ON `songs`
FOR EACH ROW BEGIN
DECLARE c integer;
SELECT COUNT(name) FROM `songs` WHERE `name`=NEW.name INTO c;
IF (c >= 1) THEN
SET NEW.newcomer=0;
ELSE
SET NEW.newcomer=1;
END IF;
END
//