J Kelly J Kelly - 1 year ago 68
MySQL Question

How do I use variables in PHP/HTML in an SQL INSERT statement

I am trying to get an html page run a php document that submits data into a table using sql. The variables are in the html page (I think, that's not my part of the project) and it runs the php document. these variables are not in the php anywhere other than this line of sql.

My code is probably very wrong here, and I'm not entirely sure how to go about this. What do I do for the VALUES? is the syntax correct? How do I import variables from the HTML/PHP into the SQL INSERT and VALUES statements?

I'm bit of a noob here, sorry.

$sql = "INSERT INTO tablename (id, last_name, first_name, username, password, gender, age) VALUES ()";

Answer Source

Firstly, you'll need to get the data using a request from a html form (read more here http://www.w3schools.com/php/php_forms.asp). You said that the html wasn't part of your project, do you at least know the name of the values being parsed to the php? If not you'll need to find out.

Next you'll need to get the values via php's $_REQUEST global array, eg: if the name of on of the values is 'name' then you would get it using $_REQUEST['name'].

In terms of inserting those values into your query, you could just jam them directly into the query string but I and others will very highly recommend you use parameterisation to protect against sql injection attacks: http://www.w3schools.com/sql/sql_injection.asp

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download