Reputation: 129
I am converting my multi dimensional post variables to dynamic variables as below:
foreach($_POST as $k => $v){
${$k} = $v;
}
So my new array looks like this:
Array(
[name] => Joe
[surname] => Blogs
[study] => Array
(
[0] => English
[1] => IT
)
[school] => Array
(
[0] => Array
(
[0] => Some School Name
[1] => 03/09/2015
[2] => Present
)
)
)
So if I want to get the school name, this code will work:
echo $school[0][0];
However, I am struggling to use this variable in an sql statement like below:
$sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '$subject[0]', '$subject[1]', '$school[0][0]', '$school[0][1]', '$school[0][2]', '$school[0][3]')";
echo $sql;
All variables that are not an array or single level array like study
are getting displayed fine but the school variables like $school[0][0]
are displaying as 'Array[0]', 'Array[1]'.........
Why is it doing this and is there away I can get those variables to display correctly?
Upvotes: 1
Views: 124
Reputation: 4823
Wrap the variable in {}, It should work. Curly braces are used to explicitly specify the end of a variable name.
Quickly...
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Wihtout curly braces PHP try to find a variable named $numberth, that not exist!
hope this helps.
Upvotes: 0
Reputation: 94672
If you wrap the arrayed values in {}
then it should work as you have it. I cannot remember the reasoning behind this but try it.
$sql = "INSERT INTO table (name, surname, subject_1, subject_2,
school1_name, school1_datefrom,
school1_dateto)
VALUES ('$name', '$surname', '{$subject[0]}',
'{$subject[1]}', '{$school[0][0]}',
'{$school[0][1]', '{$school[0][2]}',
'{$school[0][3]}')";
I remember now is called Complex (curly) syntax
Not because the syntax is complex, but because it allows for the use of complex expressions.
Upvotes: 2
Reputation: 581
replace
$sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '$subject[0]', '$subject[1]', '$school[0][0]', '$school[0][1]', '$school[0][2]', '$school[0][3]')";
with
$sql = "INSERT INTO table (name, surname, subject_1, subject_2, school1_name, school1_datefrom, school1_dateto) VALUES ('$name', '$surname', '{$subject[0]}', '{$subject[1]}', '{$school[0][0]}', '{$school[0][1]}', '{$school[0][2]}', '{$school[0][3]}')";
Upvotes: 0