Varun Goverdhan Varun Goverdhan - 1 year ago 78
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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download