I’m new to PHP and MySQL query construction. I asked a similar question yesterday about columns, and now need help with VALUES. I have a processor for a large form. A few fields are required, most fields are user optional. In my case, the HTML ids and the MySQL column names are identical. I’ve found tutorials about using arrays to convert $_POST into the fields and values for INSERT INTO, but I can’t get them working – after many hours. I’ve stepped back to make a very simple INSERT using arrays and variables, but I’m still stumped. The following lines work and INSERT the values of 5 variables into a database with over 100 columns. The first 4 items are strings, the 5th item, monthlyRental is an integer.
$colsx = array('country', 'stateProvince', 'city3', 'city3Geocode', 'monthlyRental');
$col_string = implode(',', $colsx);
$query = "INSERT INTO `$table` ($col_string) VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";
Following this idea, I use pre-processed variables to construct an array and then implode it to create a string.
//these variables are "pre-processed", e.g., $country=$_POST['country'] and validated, but not yet mysql_real_escape_string
$valsx = array( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental' );
$val_string = implode(",", $valsx);
$query = "INSERT INTO `$table` ($col_string) VALUES ( $val_string )";
It does not work. I’ve tried changing a lot of things, but with no results. The MySQL error that I get with this code is – Unknown column ‘$country’ in ‘field list’ It is referring to ‘$country’ in the $valsx array, but I don’t see how this is a field list, or how to fix the problem.
Please be specific with suggestions. I’m pretty new at MySQL and PHP.
OK, with Iserni’s suggestions, here’s the current code. It does not execute. I need help with his code, and I need help with where and how to put error messages.
$colsx = $fields = $valsx = $values = array();
$colsx = array('country', 'stateProvince', 'city3', 'city3Geocode', 'monthlyRental');
$col_string = implode(',', $colsx);
$valsx = array( "$country", "$stateProvince", "$city3", "$city3Geocode", "$monthlyRental" );
$val_string = implode(",", $valsx);
foreach($colsx as $col) {
$fields[] = $col;
if ( is_numeric($_POST[$col]) ) {
$values[] = mysql_real_escape_string($_POST[$col]);
}else{
$values[] = "'".mysql_real_escape_string($_POST[$col])."'";
}
}
$fields_sql = implode(',', $fields);
$values_sql = implode(',', $values);
$query = "INSERT INTO `$table` ($fields_sql) VALUES ($values_sql);"
if (!mysql_query($query,$conn))
{
die('<li class=error>an error occurred posting to the database. </li>'. mysql_error());
}
I’d do like this:
If you already have the validated fields, you can do it this way (but then it would be better, as I saw someone suggest, to use PDO instead of mysql_ functions; consider doing this later on).
Same thing using PDO: