user1399181
user1399181

Reputation: 313

Saving form fields to sql database - only saving numbers?

This should be so simple but it's driving me crazy. I'm trying to insert some values into a database from some form fields, but only decimals are being saved. I'm very confused.

For example, this will echo out correct values from the form fields, so I know those values are being passed along...

echo "Trying to insert $posttime, $name, $agency, $message"; 
// The above correctly outputs this: Trying to insert 1344548784, Mike, Test, Test 

But the SQL query below only works if I use numbers in the text fields, nothing else works. (I'm using phpmyadmin to confirm)

mysql_query("INSERT INTO mytable (id, from_name, from_agency, message) VALUES ($posttime, $name, $agency, $message)");

As a test, this query DOES work when I hard-code the values. I'm so confused…

mysql_query("INSERT INTO mytable (id, from_name, from_agency, message) VALUES (1344548784, 'Mike', 'Test', 'Test')");

Upvotes: 0

Views: 494

Answers (3)

CodeZombie
CodeZombie

Reputation: 5377

First of all: Stop using the deprecated mysql extension! Switch to PDO or mysqli.

Using one of these technologies you are able to use prepared statements and can pass your values as parameters. They also allow use to use the object oriented programming style.

Example:

// Assuming $link is a valid connection resource

// Prepare statement
$statement = mysqli_prepare($link, "INSERT INTO mytable (id, from_name, from_agency, message) VALUES (?, ?, ?, ?)");

// Bind parameters
mysqli_stmt_bind_param($statement, 'i', $posttime);
mysqli_stmt_bind_param($statement, 's', $name);
mysqli_stmt_bind_param($statement, 's', $agency);
mysqli_stmt_bind_param($statement, 's', $message);

// Execute
$result = mysqli_stmt_execute($statement);

This way you are not vulnerable to SQL injections.

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33532

Encapsulate your text fields with quotes when inserting data. Even though they are variables in PHP, you need to tell the database that they are strings - which is done with quotes.:

mysql_query("INSERT INTO mytable (id, from_name, from_agency, message) VALUES ($posttime, '$name', '$agency', '$message')");

Also, the mysql_* functions really are a bit dated, you should really look at moving to PDO or mysqli.

Upvotes: 1

Shawn
Shawn

Reputation: 3369

Your missing quotes:

mysql_query("INSERT INTO mytable (id, from_name, from_agency, message) VALUES ('$posttime', '$name', '$agency', '$message')")

Upvotes: 0

Related Questions