0

I'm having some serious difficulty trying to get my php sql INSERT to work. I'm trying to display user data but it just echoes, "INSERT INTO customer (cust_last, cust_first) VALUES ('user','data') Done. "

Obviously its something with the sql statement, but it is copied directly from W3Schools' example for PHP INSERT, so I'm unsure why it doesn't work. Am I not supposed to use "" or something?

Thanks for the help!

<?php
$db = odbc_connect('database1', '', '');
$sql="INSERT INTO customer (cust_last, cust_first) 
VALUES ('$_POST[cust_last]','$_POST[cust_first]')";
$rs=odbc_num_rows($conn);
odbc_close($conn);
echo "1 record added.";

?>

The HTML form page is:

<html>
<body>

<form action="insert.php" method="post">
Last Name: <input type="text" name="cust_last">
First Name: <input type="text" name="cust_first">
<input type="submit">
</form>

</body>
</html> 
3
  • To use arrays in string you need to cover them with curly braces so they become {$_POST['cust_last']}.. Also you need to watch for SQL injection Commented Aug 28, 2013 at 23:08
  • It is echoing the SQL statement because you have asked for it to be echoed. "I'm trying to display user data" That code block will not display any data. It is inserting data into the customer table. Commented Aug 28, 2013 at 23:39
  • 1
    i dont see you doing anything with the $sql variable. dont you need to pass that into some kind of function to run your query? Commented Aug 29, 2013 at 0:06

1 Answer 1

3

PHP associative arrays need single quotes around the keys, so $_POST['cust_last'] is a valid key, whereas $_POST[cust_last] isn't. Also when inserting PHP variables into strings between quotes, you should place curly braces around them.

So this would be the appropriate statement (assuming cust_last and cust_first are names of columns in your customer table):

$sql="INSERT INTO customer (cust_last, cust_first) VALUES ('{$_POST['cust_last']}','{$_POST['cust_first']}')";
Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate the help, but it still only echoes "INSERT INTO customer (cust_last, cust_first) VALUES ('user','data') Done. " (Values 'user' and 'data' do accurately reflect the entered information). My issue is that it echoes the SQL statement instead of executing it.
Well the $sql variable is only a string, si when you echo it, it will only print that string. Without knowing the specifics of the code being posted to the php, my guess, from personal experience, is that there might be a typo on the posting page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.