Ankur
Ankur

Reputation: 269

Using a php variable inside an sql query

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?

Upvotes: 1

Views: 237

Answers (2)

Felipe Francisco
Felipe Francisco

Reputation: 1063

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

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

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.

Upvotes: 2

Related Questions