Varun Goverdhan Varun Goverdhan - 7 months ago 17
SQL Question

SQL INSERT INTO table(a, b , c) VALUES (:a, :b, :c, SELECT ...)

So I'm trying to insert 4 values into a table. I'm getting 3 values from POST and the other one I want to get it from another table. This is how I thought about implementing it but it doesn't seem to be working. Any suggestions?

$query = "INSERT INTO topics (subject, data, uid, role) VALUES (:user, :pass, :uid, SELECT role FROM users WHERE uid=:uid) ";

Answer

In SQL, all subqueries need to be surrounded by their own parentheses. So, you can fix your query by using:

INSERT INTO topics (subject, data, uid, role)
    VALUES (:user, :pass, :uid, (SELECT role FROM users WHERE uid = :uid));

Personally, I much prefer the INSERT . . . SELECT version of SELECT:

INSERT INTO topics (subject, data, uid, role)
    SELECT :user, :pass, :uid, u.role
    FROM users u
    WHERE uid = :uid;
Comments