1

In my php script,i am using a php variable inside an sql query.The php variable acquires its value through a post variable as follows:

$desc0=$_POST['desc0'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$desc3=$_POST['desc3'];
$desc4=$_POST['desc4'];
$desc5=$_POST['desc5'];
$desc6=$_POST['desc6'];
$desc7=$_POST['desc7'];
$desc8=$_POST['desc8'];
$desc9=$_POST['desc9']; 

The query is:

for($i=0;$i<10;$i++)
{
$q="insert into photos(name,category,description) values ('{$name{$i}}','$category','{$desc{$i}}')";
}

The problem is that on submitting the form i am getting an error which says "undefined variable desc". Therefore its not taking the values from the previously defined variables? Any help?

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
Ankur
  • 269
  • 2
  • 4
  • 15
  • change this $desc{$i} to $desc$i and it should work – Satya Dec 25 '13 at 13:05
  • 1
    Don't build SQL queries blindly. Use [parameterized queries](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) instead. – DCoder Dec 25 '13 at 13:06

2 Answers2

3

First of, you code is completely unsafe - you should not pass user data directly into your query. There are many topics about it, and this is a good start.

Next, you don't need to store your data in such weird way. What if you'll want to pass 20 photos? In HTML, name your fields like photos[] - and in PHP, your values will be correctly parsed as an array $_POST['photos'], so you will be able to work with array:

$photos = $_POST['photos'];
foreach($photos as $photo)
{
   //$photo contains certain item, so handle it with your logic
}

Finally, your issue is because of non-obvious PHP possibility for array-dereference with curly brackets. So your $desc{$i} is an attempt to access $i-th index for non-existent array $desc. Either use $desc$i or use concatenation to separate your variables.

Community
  • 1
  • 1
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • Doyou are right.i too was not finding it appropriate to use 10 variables but i am familiar with only basic php but want to master it...Searching a proper direction.@Alma – Ankur Dec 26 '13 at 12:14
0

You must change $desc{$i} to ${"desc" . $i}

Felipe Francisco
  • 1,064
  • 2
  • 21
  • 45