PHP loop within an sql (mysql) query |
[eluser]ditch[/eluser]
Hello All, please bare with me as i'm new to programming as of 1 week ago. I'm using a combination of PHP and mysql to upload my picture paths to later be called via html and presented to the screen. Pictures are uploaded via a form with 4 image-upload inputs within the form.<-- users can upload from 1-4 images. The images paths are then uploaded to mysql table with the following column heading: image0, image1, image2, image3 Is it possible to use PHP *within* a sql query? in particular a for loop? This is what I had in mind in simple code: $sql = "INSERT INTO items (user_id,title,comment,<--for loop-->,date_created,active) VALUES ('$user_id','$item_title','$item_comment',<--for loop-->'$today','$active')"; the <--for loop--> would be something like this: for ($i=1, $i<=$count, $i++){ image[$i]; } $count = the number of images uploaded from the form Doing this would then get the query to only INSERT the images it received from the form. possible?
[eluser]rvent[/eluser]
No, you cant do that. That would be interpreted as a string and then you would get an error from mysql saying that the data could not be inserted. You gonna have to do nested loops and get the finish data into an array and then inserted it..
[eluser]ditch[/eluser]
Cheers for that... Then is it possible to specify an array within the SQL statement as a whole and have it insert all values within the array, or do you have to specify each individual value within the SQL statement?
[eluser]rvent[/eluser]
You need to process all the data you want and then do the insert. An array is just a way of doing it, but not the only one. get an idea by checking the insert section here: http://ellislab.com/codeigniter/user-gui...ecord.html
[eluser]Sarfaraz Momin[/eluser]
Well if you are using mysql 5 then you can use extended inserts. You can hack CI active record to support extended inserts. I think this is the best option available unless there is something better to be suggested.
[eluser]ditch[/eluser]
Thanx for your help guys, i fixed my issue <-- most likely the long way around it but it is working, this is how: An if & elseif (4 deep) statement to only insert the amount of images selected into the database, this way all empty fields in the database are NULL. Then when calling the images, SELECT * from the database then do a for loop with an is_null statement to skip the null values. All in all, I now get only the uploaded imaged to show on my screen without any empty spaces <-- just what I was after. Would have been struggling for another week without your help <--cheers--> |
Welcome Guest, Not a member yet? Register Sign In |