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?

2
  • change this $desc{$i} to $desc$i and it should work Commented Dec 25, 2013 at 13:05
  • 1
    Don't build SQL queries blindly. Use parameterized queries instead. Commented Dec 25, 2013 at 13:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.