Jump to content

How to add POST variables to an array for use with SQL


spryce

Recommended Posts

All of my form POST data (from multiple forms) is managed through a file called formdata.php.

 

Formdata.php and check_input() performs trim/stripslashes/htmlspecialchars etc on the posted variables. (it also indirectly calls relevant database functions such as insert or select).

 

What is the correct way to add all of the variables to an array so that I can so that I can pass the array(ofvariables) to a function.

 

ie the checked variables (only a few of them):

$subject = check_input($_POST['subject']);
$repphone = check_input($_POST['repphone']);
$repfirstname = check_input($_POST['repfirstname']);
$replastname = check_input($_POST['replastname']);
$streetnum = check_input($_POST['streetnum']);
$streetname = check_input($_POST['streetname']);
$suburb = check_input($_POST['suburb']);
$postcode = check_input($_POST['postcode']);

there will be many subjects and many more variables so instead of listing the variables such as:

function post_to_table(){
	// variables
	global $subject;, $streetnum, $streetname, $suburb, $postcode;
	global $repphone, $repfirstname, $replastname;

	if ($subject === "specifiedsubject"){
		post_to_appropriate_table($streetnum, $streetname, $suburb, $postcode, 
		$repphone, $repfirstname, $replastname);
	}

 

I would rather use an array instead of passing each variable individually:

 

function post_to_appropriate_table ($streetnum, $streetname, $suburb, $postcode
	$repphone, $repfirstname, $replastname) {

	global $database;

	$sql = "INSERT INTO incident (";
	$sql .= "streetnum, ";
	$sql .= "streetname, ";
	$sql .= "suburb, ";
	$sql .= "postcode, ";
	$sql .= "repphone, ";
	$sql .= "repfirstname, ";
	$sql .= "replastname";
	$sql .= ") ";
	$sql .= "VALUES (";
	$sql .= "'{$streetnum}', ";		
	$sql .= "'{$streetname}', ";
	$sql .= "'{$suburb}', ";		
	$sql .= "'{$postcode}', ";	
	$sql .= "'{$repfirstname}', ";
	$sql .= "'{$replastname}'";	
	$sql .= ") ";
	// echo $sql; //for debugging if required;
	return $database->query($sql);

}

 

 

how can I ditch the ever growing list of variables and use an array?

 

Thanks.

 

 

 

 

 

If the form field names are the same as the db column names, then something like this (just an example):

 

function post_to_appropriate_table($table, $data) {
    $cols = "`" . implode("`,`", array_keys($data)) . "`";
    $data = "'" . implode("','", array_map("mysql_real_escape_string", $data)) . "'";
    $sql  = "INSERT INTO $table ($cols) VALUES ($vals)";
    
    return mysql_query($sql);
}

post_to_appropriate_table("incident", $_POST);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.