PHP - While Inside A Foreach?
I get this error so I was wondering if it is because I can't put a while inside a foreach?
"syntax error, unexpected T_WHILE in home/g/h/t...." while($rows=mysql_fetch_array($rr)){ $pt_id = unserialize($rows['pts']); foreach ($pt_id as $indiv) { $q = "select * from indiv where id_incr = '$indiv'"; echo $q; $result = mysql_query($q) while $ptrow =mysql_fetch_array($result)){ echo $ptrow['v1']; echo "<br>"; } } } Similar TutorialsI want to create a loop foreach [@attributes] I seem to be stuck and cant figure it out. any info would be helpful. Thanks! Code: [Select] Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [ID] => 5760861 ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [ID] => 5335615 ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [ID] => 6080572 ) ) [3] => SimpleXMLElement Object ( [@attributes] => Array ( [ID] => 5178898 ) ) ) Hi everyone, greetings from Brazil.
I am an average php coder, much more a designer than an programer, and i am in a looper trouble..
Can anyone try to help me?
Here is my code:
<table border="1"> <tr> <?php //pega cada uma das operadoras do campo operadoras $operadoras = $opers_trazOperadoras ; $logos = explode(",",$operadoras); $x = 0 ; foreach ($logos as $v) { mysql_select_db($database_webroker, $webroker); $query_trazLogoOperadora = "SELECT * FROM tb_operadora WHERE tb_operadora.id_operadora = " . $v ; $trazLogoOperadora = mysql_query($query_trazLogoOperadora, $webroker) or die(mysql_error()); $row_trazLogoOperadora = mysql_fetch_assoc($trazLogoOperadora); $totalRows_trazLogoOperadora = mysql_num_rows($trazLogoOperadora); ?> <td><img src="http://www.we-broker...imagens_upload/<?php echo $row_trazLogoOperadora['logo']; ?>"> <?php do { ?> <?php } while ($x++ < 4); { echo $x ;?> </td></tr><tr> <?php } $x = 0 ; } ?> </table> The URL for this code is: http://valsegs.we-br...radorasPATO.php Tks! Hi.. I have table which has a data so_month: FromMonth : 5 ToMonth : 7 and I have table working_days: MonthName May Jun Jul MonthNumber 05 06 07 WorkingDays 23 24 23 Now I have function to get the 3 consecutive months from FromMonth to ToMonth , which as you can see from May to Jul Now I have problem in getting the SUM of Working days. here is my code: <?php $sql = "SELECT FromMonth, ToMonth FROM so_month"; $res = mysql_query($sql,$con); $row = mysql_fetch_assoc($res); $FromMonth = $row['FromMonth']; $ToMonth = $row['ToMonth']; function monthNames($from, $to){ $range=array(); for($i=$from; $i<=$to; $i++){ $range[$i]=date('M', mktime(0,0,0,$i)); } return $range; } $month_ = implode("' ', ",monthNames($FromMonth,$ToMonth)); foreach( monthNames($FromMonth, $ToMonth) as $month){ $sql = "SELECT MonthName, SUM(WorkingDays) AS WorkingDays FROM working_days WHERE MonthName IN ('$month') GROUP BY MonthName"; $res = mysql_query($sql, $con); while($row = mysql_fetch_array($res)){ $WorkingDays = $row['WorkingDays']; } echo $WorkingDays; } ?> the output of this code is: 232423 and when I change this line: $WorkingDays = $row['WorkingDays']; to $WorkingDays += $row['WorkingDays']; the output is: 234770 I correct output should be: 70 Any help is highly appreciated. Thank you very much.. I have a foreach loop in a webpage that displays some fields ($c), it looks like this: foreach($this->fDisplay[5] as $field) { $c = $this->field->showFieldValue($this->content,$field); if(($c !== "")&&($c !== null)) { $title = $this->field->showFieldTitle(@$this->content->catid,$field); echo "<span class='f".$field->name."'>"; if ($title != "") echo "<b>".htmlspecialchars($title)."</b>: "; echo "$c<br/>"; echo "</span>"; }
<?php function test(){ $x = ''; $arr = array('co'=>'color','ct'=>'design','cv'=>'weight','cm'=>'hight','cp'=>'price'); foreach($arr as $k=> $v){ $x .= '<tr><td> Td '.$k.' </td><td> Td '.$v.'</td></tr>' /* AFTER ACCESS THE ROW THAT DISPLAY "<tr><td> Td ct </td><td>Td design </td></tr>" */ /* insert HTML CODE (not by echo ) then complete the loop */ } return $x; } ?>
I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316454.0 I'm trying to pull results from a database (using php) to populate a javascript "top news rotation" script I found. The problem is that I'm getting the "java is disabled" message that is in the code...instead of the results I'm expecting. Here's the code: Code: [Select] <!-- create a element in your HTML like the following --> <div id="quotetext" > Text will go here. Be sure to add initial text here for users with JavaScript disabled. </div> <!-- The easiest way is to place the below JavaScript code after the above HTML. The better way would be to add in the <head> section of the document and call the rotatequote() function through the window.onload event. However this can cause problems if you have other scripts that use the window onLoad settings --> <script type="text/javascript" > var myquotes = new Array( <?php $link = mysql_pconnect($host, $username, $password); mysql_select_db('briansch_brn',$link); $sql = "SELECT * FROM story WHERE ORDER BY date DESC LIMIT 4"; $rs = mysql_query($sql,$link); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "'<strong>$row[headline]</strong><br />(posted $row[date]) - $row[short_story]<br /><a href='/pages/$row[keyword]'>READ MORE</a>'"; if($matches < 4) { echo ','; } if($matches == 4) { echo ''; } } if (! $matches) { echo (""); } echo ""; ?> ); function rotatequote() { thequote = myquotes.shift(); //Pull the top one myquotes.push(thequote); //And add it back to the end document.getElementById('quotetext').innerHTML = thequote; // This rotates the quote every 10 seconds. // Replace 10000 with (the number of seconds you want) * 1000 t=setTimeout("rotatequote()",10000); } // Start the first rotation. rotatequote(); </script> I know that javascript inside php is hard to make work...and I know that php inside javascript is hard to make work. Any ideas? Thanks! I am trying to develop a calendar. I have code to determine the number of days for each month. I want to cycle through each day and spit out code for each day. Something like the following: Code: [Select] <?php $month = "December"; $days = 31; foreach($days){ echo "<div id='day_block'> ".$days." </div>"; } ?> i think i need to use a counter but don't know how, any help would be awesome! Hi All, I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each property that is associated with the search: <ul> <?php foreach($properties as $property) { ?> <li><?=$property->$zipcode?></li> <?php } ?> </ul> How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code? Thanks in advance! P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors. Anyways, thanks in advance for the help! Hi! When I echo $m below, it will show all selected options fine. Instead, I want it to show many I selected. So if I selected 3 in dropdown, I want it to say I selected 3 instead of showing their values. $allmaps=$_POST['maps']; foreach ($allmaps as $m) { echo 'm = '.$m.''; } <select name="maps[]" multiple>'.$maps.'</select> I appear to be having a simple simon day! my foreach is only displaying the last result in the table as opposed to each row $num_rows = mysql_num_rows($query); echo "There are $num_rows records.<br>"; while($row = mysql_fetch_row($query)) foreach ($row as $field) { echo '<div class="results">'; echo $field; echo '<br></div>'; } And the source Code: [Select] <link href="../styles/clientbox.css" rel="stylesheet" type="text/css"> <body><br> <h3>My Services</h3> <div class="text"> You currently have the following services with us: </div> There are 2 records.<br><div class="results">test1<br></div> </body> </html> My table has 2 rows which the 1st one has a package of test and the second a package of test1 Can anyone help? Thanks i have a table that echos 10 entries what i want to do is once it echos 5 records it starts a new table. I dont know how to go about this. Could you guys guide me the right way. Hi i am trying to pass values from a cart to a database using foreach. This is my code: Code: [Select] $columns = array('order_id', 'order_item_id', 'order_product_name', 'order_product_dimensions', 'order_product_options', 'order_product_quantity', 'order_product_price', 'order_product_subtotal', 'order_product_vat', 'order_product_delivery','order_product_total','order_product_sku','order_product_image_name','order_product_image_type','order_product_image_path','order_product_image_size','order_product_artwork_link','order_product_artwork_name','order_product_artwork_type','order_product_artwork_path','order_product_artwork_size','order_firstname','order_lastname','order_companyname','order_email','order_tel','order_billing_address','order_billing_address2','order_billing_town','order_billing_county','order_billing_postcode','order_shipping_address','order_shipping_address2','order_shipping_town','order_shipping_county','order_shipping_postcode','order_status','order_username'); $data = array_fill_keys($columns, 'NULL'); foreach($data as $key => $value) { $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_escape_string($_POST[$key])."'"; $query = "INSERT INTO orders (id, order_created_at, ".implode(", ",$columns).") VALUES (null, NOW(), ".implode(",",$data).')'; } Problem is posting 2 or more products into the database. How do i split the values so it enters each product into the database? public function update($data, $table, $where) { foreach ($data as $column => $value) { $sql = "UPDATE $table SET $column = $value WHERE $where"; print "table: ".$table." column: ".$column." whe ".$where; mysql_query($sql) or die(mysql_error()); } return true; } $data: $data = array( "username" => "Jack", "email" => "jack.gmail@gmail.com" ); $db->update($data, "users", 'id=1'); Working on this code that updates a column from a class. Everything is fine except for one issue. As of right now $column is set to "Jack" which outputs an error, instead of what it should be as "username". I'm sure it's something really simple, so any assistance is appreciated. Any ideas? Problem area is listed in red. Hi guys, Having a bit of trouble getting this to work. I should say before I start that im a rookie at PHP. Basically this is the code I have {counter start=0 print=false name=competcount} {foreach item=compet from=$person.competition} <img src="./bargraph/bar.php?value={$person.lineup[$compet.id].titular}&max={$club.matchsplayed[$compet.id].nummatchs}&info" /> The problem lies with the $club array not being defined Code: [Select] $club.matchsplayed[$competition.id].nummatchs How do I set up multiple arrays with foreach? Am I even in the right ball park with this? In the code I want to proceed to the next step only after stripslashes and strip_tags are completed. How do I put the code below with if? $stripped = array('name', 'location', 'bio'); foreach ( $_POST as $k => $v ) { if ( in_array($k, $stripped) ) { ${$k} = strip_tags($v); } } foreach ( $_POST as $p => $q ) { if ( in_array($p, $stripped) ) { ${$p} = stripslashes($q); } } Thanks, Ruth. |