Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Insert into mysql from simple form 1

Status
Not open for further replies.

dugen

Programmer
Jun 16, 2003
59
US
I am trying to insert data from a text box on a form to a mysql database. The connection to the database is working, and there is a form with the field txtFirstName thats action points to the page below. I think the problem has to be the query. When the code is executed it enters a blank field into the database even when there is text in the txtFirstName text box.

I would appreciate some help.

Thanks.

<?php

// Connect To Database

$host = "db";
$user = "abc";
$password = "pword";
$db_name = "list";
// connecting to the database on battcave.com
$link = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db("list") or die(mysql_error());

$query = "INSERT INTO list (name) VALUES ('$_POST[$txtFirstName]')";

mysql_query($query) or die('Error, query failed');
// Insert a row of information into the table "example"
echo "Data Inserted!";


?>
 
Section 1.5 of faq434-2999 deals with this sort of thing.

Part of the advice I put in there is when a query does not behave as you expect to output it to the browser and examine it. Does it look right?

On first blush, I would think that it's your reference to $_POST[$txtFirstName]. Nowhere in the script do I see you seting a value to the variable $txtFirstName. In fact, I'm suprised you don't get a warning about this, and if you're not, you should if possible set the error-reporting threshold in PHP lower.

Anyway, if the form field which contains the data is named "txtFirstName, you need to reference that. Since PHP isn't too keen on associative array references inside interpolated strings, I use concatenation. My version of the line which creates the query would have been:

$query = "INSERT INTO list (name) VALUES ('" . $_POST['txtFirstName'] . "')";



Want the best answers? Ask the best questions! TANSTAAFL!
 
Like sleipnir214 says a good way to troubleshoot the query is just to output the sql onto the screen.
i.e. after the line,
Code:
$query = "INSERT INTO list (name) VALUES ('$_POST[$txtFirstName]')";

// output the sql query to the screen via

echo $query;
Then running it again will give you an indication to what its trying to insert into the table (before it hits the die function), if it still looks ok on screen, copy it from the screen and run it from a MySQL window as it may be an incompatible field type within the table thats causing your issue.

FAM
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top