0
$query = "INSERT INTO `posts` (title, author, body, tags)
                VALUES (`$title`, `$author`, `$body`, `$tags`)
                (SELECT * FROM category WHERE name = $category)";

posts and category both are different tables?

Dharman
  • 30,962
  • 25
  • 85
  • 135
kropani
  • 19
  • 8
  • Short answer, no.. For starters, your php variables `$title`, etc should be in inverted commas – gaganshera Apr 25 '17 at 10:20
  • `queries` depends on backend database, not PHP – Priyesh Kumar Apr 25 '17 at 10:20
  • $q = "INSERT INTO `posts` (title, author, body, tags) VALUES (`$title`, `$author`, `$body`, `$tags`) (SELECT * FROM category WHERE name = $category)"; Still showing syntax exception @gaganshera – kropani Apr 25 '17 at 11:35
  • `INSERT INTO posts (title, author, body, tags) VALUES ('$title', '$author', '$body', '$tags')`; – gaganshera Apr 25 '17 at 11:37
  • Possible duplicate of [When to use single quotes, double quotes, and backticks in MySQL](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – Dharman Jun 13 '19 at 22:17

1 Answers1

0

If you have variables with the values:

$etitle = somehow_escape($title); ...
INSERT INTO posts
          (title, author, body, tags)
          VALUES
          ('$etitle', '$eauthor', '$ebody', '$etags');

If fetching the values from another table:

INSERT INTO posts
          (title, author, body, tags)
    SELECT title, author, body, tags
        FROM category
        WHERE ...
  • You must escape the values -- Think about what would happen if a ' were in the $title!
  • When using SELECT with INSERT, there is no VALUES cause.
  • No need for the parens around the SELECT subquery (in this situation).
Rick James
  • 135,179
  • 13
  • 127
  • 222