插入选择查询

时间:2013-05-17 14:19:21

标签: mysql sql

我有2个表格和用户。

我想在文章表中插入标题,内容和名称。

我有一个存储在会话中的用户ID,有没有办法使用插入选择查询将标题,内容和名称添加到文章表中,同时使用id从users表中获取名称。

类似的东西:

INSERT INTO article (title, content, name) VALUES ($post['title'], $post['content'], name) SELECT name FROM users WHERE id = mySessionId

1 个答案:

答案 0 :(得分:3)

使用INSERT INTO..SELECT语句,

$title = $post['title'];
$content = $post['content'];
$insertStatement = "INSERT INTO article (title, content, name)  
                    SELECT '$title', '$content', name 
                    FROM users 
                    WHERE id = mySessionId";

作为旁注,如果变量的值( s )来自外部,则查询易受SQL Injection攻击。请查看下面的文章,了解如何防止它。通过使用PreparedStatements,您可以摆脱在值周围使用单引号。

相关问题