Link to home
Start Free TrialLog in
Avatar of Jazzy 1012
Jazzy 1012

asked on

Insert won't work due to space in column name

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$username= "jasmine";

require "connection.php";

$data = isset($_POST['data']) ? $_POST['data'] : false;


if (is_array($data)) {
	// LOOP THOUGH EACH SUBMITTED RECORD
	$updatestr = 'Gathered /By, Date,';
	$update1 = '';
	$update1 .= "'" . $username . "',";
	$update1 .= "'" . date("d/m/Y") . "',";

		foreach($data as $field => $value) {
			$value=mysqli_escape_string($conn, $field);
			$value=mysqli_escape_string($conn, $value);
			$updatestr .= "{$field },";
		

			trim($updatestr, ',');
			
		
		}
		$updatestr= rtrim($updatestr,',');
		foreach($data as $field =>$value){
			$value=mysqli_escape_string($conn, $value);
			$update1 .= " '{$value}',";
			
			trim($update1, ',');
			
		}
		$update1= rtrim($update1,',');
			$query = "INSERT INTO `rsvp` ({$updatestr}) VALUES ({$update1})";
			// SEND IT TO THE DB
			$result= mysqli_query($conn, $query);
			echo "working";


}
else {
	echo "Error occurred.";
}


?>  

Open in new window


I have this code, but it everything is fine but my only issue is that it won't add into the query since one of my columns have a space : "Gathered By"
this is the output of my query
INSERT INTO `rsvp` (Gathered By,Date ,First ,Last ) VALUES ('jasmine','26/01/2017', 'Jazz', 'Jazz');

Open in new window

How can I fix this? I cant change the column name, so is there anyother way ?
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
btw, I see these 2 lines:
$value=mysqli_escape_string($conn, $field);
$value=mysqli_escape_string($conn, $value);

the first of the 2 is obsolete, you can remove that one
Avatar of Jazzy 1012
Jazzy 1012

ASKER

No it still doesn't work
I just had to add `` to Gathered By statically since it was written it wasn't in fields, thanks!
I see:
$updatestr = 'Gathered /By, Date,';
=> $updatestr = '`Gathered /By`, `Date` ,';

and you should also do this:
$update1 .= "'" . mysqli_escape_string($conn,  $username ) . "',";