insert array with dynamic amount of values to database - php

I am attempting to insert an array of image information into my database. The array consists of a ton of image information and originally i started with just allowing 3 images out of the array to be entered into the database.
The images detail goes into a table called print and each of the three image urls has a column of their own to go into, along with a caption for each image, the date the image was taken and its location. All of this info goes into one row with the users id.
// Assign images and data to appropriate variables
$image_one = $feed['0']['images']['standard_resolution']['url'];
$image_one_caption = htmlspecialchars($feed['0']['caption']['text'], ENT_QUOTES);
$image_one_date = $feed['0']['created_time'];
$image_one_location = $feed['0']['location']['name'];
$image_two = $feed['1']['images']['standard_resolution']['url'];
$image_two_caption = htmlspecialchars($feed['1']['caption']['text'], ENT_QUOTES);
$image_two_date = $feed['1']['created_time'];
$image_two_location = $feed['1']['location']['name'];
$image_three = $feed['2']['images']['standard_resolution']['url'];
$image_three_caption = htmlspecialchars($feed['2']['caption']['text'], ENT_QUOTES);
$image_three_date = $feed['2']['created_time'];
$image_three_location = $feed['2']['location']['name'];
However I now want to make it so that the number of prints entered into the table can vary from 3 up to 10 as a maximum. I'm wondering about the best way to do this.
I could simply assign the array values to more variables in the way shown above, however this is bulky and I feel unnecessarily repetitive.
I was thinking about a foreach loop, however I'm uncertain of how to insert each image and each images accompanying data into the correct columns of the users print row.
The other option would be to create a separate print_info table and store the users id and print_job number, then in the print table purely have the image info in separate rows with a print_job column to link the print_job to the users print_info row. is this the best way forward with this little problem?

What about this:
$numOfImages = 4; //the number you want
for ($i=0; $i < $numOfImages; $i++) {
$image = $feed[$i]['images']['standard_resolution']['url'];
$image_caption = htmlspecialchars($feed[$i]['caption']['text'], ENT_QUOTES);
$image_date = $feed[$i]['created_time'];
$image_location = $feed[$i]['location']['name'];
//...operation with $image
}

Related

Looping through multi-dimensional array to pre-populate dynamically generated form

I am trying to create an ecommerce site. I have products that have different attributes (e.g. colour) and each of these needs to have their own model number and price etc,.
I have generated a form to gather this information and save it. However, I want to be able to save this info as a $_SESSION variable while users are adding products, so that they can come back to the price section and the form will be pre-populated with what they previously entered even though they haven't actually saved the product to the DB yet.
To do this I have a string that I treat as an array of items stored as a $_SESSION variable in PHP in the following format:
'item-test,100,20,20,20,20,£,1,item-test,100,20,20,20,20,£,2'
I parse this into an actual array I can deal with like so (when it gets to actually saving the product my SQL query is inside this foreach() loop):
if(isset($_SESSION['price_array'])){
$price_array = $_SESSION['price_array'];
$result = explode("item-",$price_array);
foreach($result as $item){
if(isset($item) && $item!=""){
$itemValue = explode(",",$item);
$product_model_no = $itemValue[0];
$product_value = $itemValue[1];
$product_discount = $itemValue[2];
$product_margin = $itemValue[3];
$product_shipping_domestic = $itemValue[4];
$product_shipping_other = $itemValue[5];
$product_currency = $itemValue[6];
$product_attribute = $itemValue[7];
}
}
}
So to generate this form I've another loop that goes through all of the possible attributes (not all products might come in all colours so only the ones stored in the $_SESSION apply). If I try to pre-populate this as it is my variables above only have the values for the last item in the array.
However if I nest this inside the other loop it will get the correct data but it will generate the form a number of times depending on how many items are in the array, with each iteration of the form having the values for that item in the array.
I know this is very convoluted to try explain and I can't really provide all my code because it is very complex and most of it is generated in PHP from other information in other locations.
Edit
The basics of how the form is being generated inside the other loop is as follows:
$params = [$attribute];
$sql = "SELECT * FROM attributes WHERE id=?";
$attributeResult = DB::run($sql,$params);
foreach ($attributeResult as $value) {
for ($i = 1; $i <= 15; $i++) {
//generate form here
if($i == $product_attribute){
// pre-populate form here
}
}
}

Getting value from multiple drop down menus in PHP

Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.

storing array data in mysql

I am new to PHP and MySQL, please I would appreciate your help.
I have a table that generates several rows depending on the number of options selected by a user.
I want to store the content in a database table after the user presses the submit button.
Since i cannot tell how may options the user would select and how many rows will be generated, i don't know how to write the SQL code that will store it in my database table.
here is the code to generate the table
for($x=0;$x<$N; $x++) {
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea></td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
To get the data from the table
for($i = 0; $i <$N; $i++){
$data[] = array(($art[$i]), ($science[$i]), ($method[$i]), ($criteria[$i]));
}
I would normalize this design and have a USER and OPTION table with a one-to-many relationship between them. You have as many rows as you do selections that way. You can query later to see how many USER rows chose OPTION X.
You can merge (implode) all values and store into table. split ( explode ) the values while retrive.
Store :
$optionsVal = implode(",", $data);
Retrieve :
$data = explode(",", $optionsVal);

Get a random number betwen 1-200 but leaves out numbers read from query

I need to get a random number between, lets say 1-200, but at the same time I need to prevent selecting a random number that has already been used for a particular REMOTE_ADDR (as stored in a table).
This is what I have so far (I have tried several different approaches):
$ip = $_SERVER['REMOTE_ADDR'];
$query7 = "
SELECT *
FROM IP
WHERE IP = '$ip'
";
$result7 = mysql_query($query7) or die(mysql_error());
$rows7 = mysql_num_rows($result7);
while ($row7 = mysql_fetch_array($result7)){
$id = $row7['ID'];
}
I'm using the random number to pick an image to display, but my users are complaining that the images selected for them is not random enough; ie, the same picture is getting "randomly" selected too often, sometimes showing the same image over and over.
It does not have to be in PHP, if there is another option.
Something like that
// all ids from 1 to 100
$all = array_fill(1, 200, 0);
// remove used
foreach ($used as $i) {
unset($all[$i]);
}
// get survived keys
$keys = array_keys($all);
// get random position, note that the array with keys is 0 based
$j = rand(0, count($all) - 1);
return $keys[$j];
Run your select and instead of using *, only select the id column. Then use:
while($row7[] = mysql_fetch_array($query7));
do{
$rand = rand(0,200);
}while(in_array($rand,$row7));
You can do it all in mysql. Have one table that has your list of images, and another table that has the list of IP addresses and the images that have already been shown to that IP. Then you select and join the tables and order the result randomly.
SELECT image_id FROM images
LEFT JOIN shown_images ON images.image_id=shown_images.image_id AND ip_addr=[#.#.#.#]
WHERE shown_images.image_id IS NULL
ORDER BY RAND() LIMIT 1;
After you show an image to an IP, just insert a record into the shown_images table with the IP and the image ID. That will work right up until that have seen all the images. Then you can delete the records and start over.
This answer assumes that you have 200 items, and collect the items which you do not want to show. Alternatively, you can query only id's of available items and choose from these, you would need to create a table with available items for that.
Create a map which maps consecutive numbers to (non-consecutive) available numbers. Suppose the numbers 1 and 3 are in use, you can map to 2 and 4 (and so on).
Actually, it is possible to use a simple array (not-associative) for this. You can do something like this:
$reserved = array(1, 3); // fill $reserved using your code
$available = array();
for ($i = 1; $i <= 200; $i++) {
if (!in_array($i, $reserved)) {
$available[] = $i;
}
}
if (count($available) > 0) {
$random_index = rand(0, count($available) - 1);
$r = $available[$random_index];
} else {
// Nothing available!
}
There will be nothing to choose when you run out of pictures that have not been displayed yet. In this case, count($available) will be zero. One way to solve this would be to clear your list of displayed images for the current IP and choose again; see also other answers for this.

Save multiple rows with multiple arrays - PHP

I have a big problem on saving multiple rows with multiple arrays into MYSQL. For example row 1 contains "name" and "share percentage". Then they add another 2 rows which contains same attributes as mentioned. So how do I save these data into DB. Below was my unsuccessful code:
foreach($_POST['name_members'] as $dir){ // array 1
$directorID = run_num('director_id','proc_director'); // generate running number for each row
foreach($_POST['share_percentage'] as $share) { //array 2
$insDirector = "INSERT INTO
proc_director(director_id, vendor_cd, director_name, director_percentage)
VALUES
('$directorID','$vendorID','".trim(addslashes($dir))."','$share')";
$db->query($insDirector); // save the array value into DB
}
}
I made demo interface, so that you can get the picture what I want. Here the hyperlink: http://softboxkid.com/blog/code/add_row/
Thank for your respond. I already found the solution for my problem. Here is my code:
/* save partnerhip information */
$count_director = count(array_trim($_POST['name_members']));
for($i=0; $i<$count_director; $i++) {
$directorID[] = run_num('director_id','proc_director'); // generate running number for each row
$insDirector = "INSERT INTO proc_director(director_id, vendor_cd, director_name, director_percentage)
VALUES('".$directorID[$i]."','".$vendorID."','".$_POST['name_members'][$i]."','".intval($_POST['share_percentage'][$i])."')";
$db->query($insDirector); // save the array value into DB
}

Categories