7

I am trying to create an SQL query to insert user info into a database. The $fname and $lname variables contain correct values ("John" and "Doe") but the query fails. Here is my code:

$fname = $_POST['first_name'];
$lname = $_POST['last_name'];  
$sql = "INSERT INTO users (fname, lname) VALUES ($fname, $lname)";
mysqli_query($conn, $sql);

after checking the error message I've found that this query fails with error saying

Unknown column 'John' in 'field list'

How can I properly include variables into SQL query to make it run without an error?

  • This question is not about SQL syntax which I am quite familiar with, but about the rules of creating a query dynamically using variables in a PHP script.
  • I don't want a quick patch that only eliminates the immediate error, but a state-of-art solution which is error free and secure as well.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 3
    I appreciate that you're trying to setup some authoritative dupe targets, but "it fails" has never been a valid problem statement here. You need to expand the description of the problem and indicate under what conditions a syntax error would be generated, and (ideally) include a textual representation of the actual error so people can find this question via Google instead of one of the countless others that *does* include real error messages. – user229044 Feb 24 '17 at 15:08
  • "Unknown column 'hello' in 'field list'" - How is that possible? – Paul Spiegel Feb 26 '17 at 04:43
  • This is confusing, but you're right (just tested). Maybe you should include a dump of user input (`var_dump($name); // output: ...`) to show that it's not numeric. And I would choose another example to avoid comments like "Don't store passwords in plain text!" – Paul Spiegel Feb 26 '17 at 04:56
  • @PaulSpiegel good points, thank you – Your Common Sense Feb 26 '17 at 05:06
  • 7
    @YourCommonSense Please stop closing `mysqli_*` questions as duplicates of this one. This is not an appropriate dupe target. This is confusing for people who are writing new code using MySQLi and completely impractical for people working on existing apps which already use MySQLi. Regardless of your preference for PDO, this is *not* the same question as somebody encountering problems with MySQLi, and your answer below is completely irrelevant to those people. – user229044 Feb 27 '17 at 14:18
  • @meagar I do not close "mysqli" questions as duplicates of this one. But questions where the issue is caused by this very exact problem only. – Your Common Sense Feb 27 '17 at 14:25
  • @meagar I can rewrite this code to procedural mysqli as well. I just had no idea it's that important. – Your Common Sense Feb 27 '17 at 14:37

0 Answers0