0

Is this right way to right prepared statement when you have to run select stement inside value which is usually values(?)

   function permission_table($conn, $username) {
    if($stmt = $conn->prepare("INSERT INTO perm (user_id) VALUES(SELECT id FROM users WHERE username = ?)")) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
}
}
Jskccc
  • 21
  • 5

1 Answers1

0

I would just directly use an INSERT INTO ... SELECT here, without the VALUES clause:

INSERT INTO perm (user_id)
SELECT id FROM users WHERE username = ?;

Your updated PHP code:

$sql = "INSERT INTO perm (user_id) SELECT id FROM users WHERE username = ?";
if ($stmt = $conn->prepare(sql)) {
    $stmt->bind_param("s", $username);
    $stmt->execute();
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360