Alex_TCD Alex_TCD - 8 months ago 32
SQL Question

How to update an SQL database with form data using PHP?

How do I get html form POST data to appear after the = signs?

$tsql = "UPDATE dbo.[order]
SET status=''
WHERE order_ID='' ";


POST data can be retrieved using the $_POST suberglobal like this:

.... " SET status = '{$_POST['form_field_name']}'";

HOWEVER, I would recommend using prepared statements for this whenever possible. Putting form data directly into an SQL statement is a bad practice and can cause security issues.

You should use a prepared statement like this:

// Store the form data in variables
$status = $_POST['status_field'];
$order_ID = $_POST['order_ID_field'];

// Extra protection to prevent SQL Injection
$sanitized_status = mysqli_real_escape_string($dbConnection, $status);
$sanitized_order_ID = mysqli_real_escape_string($dbConnection, $order_ID);

// Prepare the SQL 
// When script is run database will compile this statement first
$stmt = $dbConnection->prepare('UPDATE table_name SET status = ? WHERE order_ID = ?');
// Parameters are bound to the COMPILED statement not the string
$stmt->bind_param('si', $sanitized_status, $sanitized_order_ID);


PHP will compile the SQL statement first, and then later add in the parameter values.

Reference: How can I prevent SQL-injection in PHP?