PHP - Looping Through My Query
I am trying to loop through the array that I have created to check to see if any of the dates in the array match the date I am passing (which is todays date) and then asks the user to consider making another booking.
This is what I have so far but I am not sure how to finish it off: Code: [Select] $table_id = 'booking'; $query = "SELECT * FROM booking WHERE bookingDate = 'newDate'"; $result = mysql_query($query); $loop = $end_Time - $start_Time; echo $loop; while($row = mysql_fetch_assoc($result)){ if ($startTime || $end_Time == 'booking.startTime'){ echo "choose another booking"; }{ echo "booking is ok"; } Similar TutorialsSorry, I originally posted part of this in MYSQL Help, but I was advised to post it here. I'm hoping someone can help me out. I have 2 tables. "categories" and "subcats" (sub categories). I used a JOIN query for both.. Code: [Select] SELECT categories.*, subcats.* FROM categories JOIN subcats on (categories.cat_id = subcats.cat_id) ORDER BY cat_name Then I used a while loop to echo all the categories from the "categories" table and their respective sub-categories from the "subcats" table. $sql = "SELECT categories.*, subcats.* FROM categories JOIN subcats on (categories.cat_id = subcats.cat_id) ORDER BY cat_name"; $cats_result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $cats_result->fetch_assoc()) { $cat_id = $row['cat_id']; $cat_name = $row['cat_name']; $subcat_name = $row['subcat_name']; //should output all categories once and nest their subcategories echo "<strong>".$cat_name."</strong>"; echo "<br />"; echo $subcat_name; echo "<br />"; } No MYSQL errors but unfortunately I get this output.. Technology Computers Technology Gadgets Technology Robots Health Fitness Health Diet What sort of code can use in the loop to echo categories just once instead of multiple times for each topic? Hey guys. Just need some help on how I can add a query on row 2 if let's say a field is populated (Ex. spouse != null). Here is the code but having a hard time trying to put that 2nd row while it's looping. Any help would be appreciated. Thanks! $data = ''; while ( $row = mysql_fetch_row($export)) { $line = ''; foreach ( $row as $value ) { if ( ( !isset($value) ) OR ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace('"', '""', $value); $value = '="' . $value . '"' . "\t"; // ^ // Added an equal sign } $line .= $value; } $data .= trim($line)."\n"; } $data = str_replace("\r", "", $data); // return message if query returns no data if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } // setup headers with no caching header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=data.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; } else { Apologies if this should be in the mysql forum but hopefully this is the correct one. I am trying to extract the sum of a column from my database for each financial year, at the moment I am doing each year as a separate recordset but I am certain there must be a more automated way! The financial year is 1st April to 31st March each year and I need to create a variable which is a sum of each year, you'll see in my code below what I mean, any help gratefully appreciated as I am going to end up with decades of info in the db and am keen to get the code right now! The relevant recordsets are 2,5,7. db is readingID, date, reading The code and page does work fine, it's just long winded! Code: [Select] <?php mysql_select_db($database_wind, $wind); $query_Recordset1 = "SELECT readingID, date_format(date,'%d/%m/%Y') as date, reading FROM solar ORDER BY readingID DESC LIMIT 5"; $Recordset1 = mysql_query($query_Recordset1, $wind) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); $totalRows_Recordset1 = mysql_num_rows($Recordset1); mysql_select_db($database_wind, $wind); $query_Recordset2 = "SELECT SUM(reading) as year1total FROM `solar` WHERE date between '2010-04-01' and '2011-03-31'"; $Recordset2 = mysql_query($query_Recordset2, $wind) or die(mysql_error()); $row_Recordset2 = mysql_fetch_assoc($Recordset2); $totalRows_Recordset2 = mysql_num_rows($Recordset2); mysql_select_db($database_wind, $wind); $query_Recordset3 = "SELECT * FROM solar ORDER BY readingID DESC Limit 29"; $Recordset3 = mysql_query($query_Recordset3) or die(mysql_error()); mysql_select_db($database_wind, $wind); $query_Recordset4 = "SELECT readingID, YEAR(date) as yeardate, MONTHNAME(date) as monthdate, SUM(reading) as sumreading FROM `solar` Group by yeardate, monthdate Order by readingID ASC"; $Recordset4 = mysql_query($query_Recordset4) or die(mysql_error()); mysql_select_db($database_wind, $wind); $query_Recordset5 = "SELECT SUM(reading) as year2total FROM `solar` WHERE date between '2011-04-01' and '2012-03-31'"; $Recordset5 = mysql_query($query_Recordset5, $wind) or die(mysql_error()); $row_Recordset5 = mysql_fetch_assoc($Recordset5); $totalRows_Recordset5 = mysql_num_rows($Recordset5); mysql_select_db($database_wind, $wind); $query_Recordset6 = "SELECT datediff( Max(date), Min(date)) as DateDiff, Sum(reading) as LatestReading, date_format(MAX(date),'%d/%m/%Y') as LatestDate FROM solar"; $Recordset6 = mysql_query($query_Recordset6, $wind) or die(mysql_error()); $row_Recordset6 = mysql_fetch_assoc($Recordset6); $totalRows_Recordset6 = mysql_num_rows($Recordset6); mysql_select_db($database_wind, $wind); $query_Recordset7 = "SELECT SUM(reading) as year3total FROM `solar` WHERE date between '2012-04-01' and '2013-03-31'"; $Recordset7 = mysql_query($query_Recordset7, $wind) or die(mysql_error()); $row_Recordset7 = mysql_fetch_assoc($Recordset7); $totalRows_Recordset7 = mysql_num_rows($Recordset7); $average = (int)(($row_Recordset6['LatestReading'])/($row_Recordset6['DateDiff'])); $income1 = $row_Recordset2['year1total']*0.428; $income2 = $income1 + $row_Recordset5['year2total']*0.464; $income = $income2 + $row_Recordset7['year3total']*0.464; $saving = $row_Recordset2['year1total']*0.0675; $saving = $saving + $row_Recordset5['year2total']*0.0675; $saving = $saving + $row_Recordset7['year3total']*0.0675; ?> I am pulling data from an sql data base. I want it to displayed (Item # | Error button | Link) however as its looping with a while on the database info I cant seem to get it to loop on the item number so it shows 1, 2, 3,.... on each row. Current coding is: while ($info = mysql_fetch_array($data)){ Print '<tr>'; Print"<td style='width: 15px;' class='cat-list'>$D</td>"; if ($info['id']==""){ Print"<td class='cat-list'> </td>"; }else{ Print"<td class='cat-list' style='width: 20px;'><img border='0' src='images/error.png' width='16' height='16'></td>"; } if ($info['link']==""){ Print"<td class='cat-list'> </td>"; }else{ Print"<td class='cat-list'><a target='_blank' href='".html_entity_decode(stripslashes($info[link]))."'>".substr(html_entity_decode(stripslashes($info[link])), 0, 85)."</a></td>"; } } How would I get the $D item to show 1 2 3... ect? Thanks, Jim Take a look he http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=YahooDemo&query=test That is a generated XML file from Yahoo's API. If you take a look, it has a node titled "Question". With PHP, how can I loop through each "Question" node and grab all of it's children as well? I tried this code, but apparently it did not work: $req = "http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=YahooDemo&query=php"; $res = file_get_contents($req); $xml = simplexml_load_string($res); foreach ($xml->xpath('//Question') as $question) { // "//question" means for each question node echo((string)$question['Subject']." - ".(string)$question['Content']); // you get all the child nodes in $question } How come this doesn't loop? Everything is in the while loop.
My database connection is in the included file you see to begin the code which is what db_conx refers to just to be clear. Database connection is not an issue nor is getting values. I just get the first one and nothing more. No looping taking place here.
What I miss?
require('includes/db_connect.php'); $query = "SELECT * FROM events ORDER BY displayorder ASC"; $result = mysqli_query($db_conx, $query); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $pid = $row["id"]; $title = $row["title"]; $date = $row["date"]; $info = $row["info"]; $linkTxt = $row["linkTxt"]; $link = $row["link"]; $message = "<div id='events_holder'><table width='500' border='0' cellspacing='0' cellpadding='10'> <form action='edit_event_parse.php' method='post'> <tr> <td class='prayer_title'>Title:</td> <td><input type='text' name='title' class='admin_input' value='" .$title."' /></td> </tr> <tr> <td class='prayer_title'>Date:</td> <td><input type='text' name='date' class='admin_input' value='".$date."' /></td> </tr> <tr> <td class='prayer_title'>Link Text:</td> <td><input type='text' name='linkTxt' class='admin_input' value='".$linkTxt."' /></td> </tr> <tr> <td class='prayer_title'>Link URL:</td> <td><input type='text' name='link' class='admin_input' value='".$link."' /></td> </tr> <tr> <td class='prayer_title'>Event Details:</td> <td><textarea name='info' cols='20' rows='10' class='admin_area'>".$info."</textarea></td> </tr> <tr> <td><input type='hidden' name='pid' value='".$pid."' /></td> <td><input name='submit' type='submit' value='Edit Event' class='admin_submit'/></td> </tr> </form> </table> <p> </p> <hr /> <p> </p> </div>"; }Thanks! ANYONE WHO CAN HELP ME WITH MY LOOP? THIS IS THE CODE THANKS IN ADVANCE.
<?php $testTwo = 'bakit ayaw po gumana paulit ulit bakit'; $testOne = 'bakit paulit ulit bakit ulit'; $tTwo = explode(' ', $testTwo); $tOne = explode(' ', $testOne); echo"SIMILARITIES:</br>"; foreach($tOne as $first) { foreach($tTwo as $second) { if($second == $first) { echo $second.' '; } } echo"</br>"; } ?> THIS IS THE OUTPUT SIMILARITIES: bakit bakit paulit ulit bakit bakit ulit THIS IS MY EXPECTING OUTPUT. bakit paulit ulit bakit ulit lang ok, here is some code: Code: [Select] <?php // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM products"); while($row = mysql_fetch_array($sql)){ $product = $row["product"]; ?> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#myform").validate({ debug: false, submitHandler: function(form) { // do other stuff for a valid form $.post('process.php', $("#myform").serialize(), function(data) { $("#price").load("index.php #price"); $('#results').html(data); }); } }); }); </script> <form name="myform" id="myform" method="POST" action=""> <input type="hidden" name="hiddenField" id="hiddenField" value="<?php echo $product; ?>" /> <input type="submit" name="submit" value="Submit" style="background-color:lightgreen; height:50px; width:100px;"> </form> <?php } ?>and here is process.php Code: [Select] <?php include_once("/connect.php"); ?> <?php $price=$_POST['hiddenField']; $sql = "INSERT INTO cart (price) VALUES('$price')"; $rs = mysql_query($sql) or die ("Problem with the query: $sql<br>" . mysql_error()); echo mysql_error(); ?>. what is happening is it is supposed to be submitting form without page reload.......but only the first one in the loop does it. I want all of them to do it. can anyone help me do this properly. ok I'm a bit stuck here were I would think something would work easily im getting an error. What I am trying to loop is.. $data="UPDATE ts12 SET djid='$_POST[TS0]' WHERE id=1"; $data="UPDATE ts12 SET djid='$_POST[TS1]' WHERE id=2"; This would go on for 84 id's. So I figured I could just loop this line so I only have to type it once. Right now I have it set up for just testing 7 ids and I have this code.... if ($edit == yes) { for ($i=0; $i < 7; $i++){ $n=($i+1); $data.="UPDATE ts12 SET djid='$_POST[TS$i]' WHERE id=$n"; } if (!mysql_query($data,$con)) die('Error: ' . mysql_error()); }else{} The error I am getting is... PHP Parse error: syntax error, unexpected T_VARIABLE, expecting ']' in dir/page on line 6 What am I doing wrong here? i have this bit of code which is supposed to do a while loop of rows from a database then inside that does a while loop of columns, so its basically creating a html table of dynamic data from mysql. the column loop works fine, but the row one isnt, it only goes through and echos out the first row then stops. ive spent hours now trying to see why and i cant see it hence my call for help. $totalrows = 4; $columns = 5; $columncount = 1; $rowcount = 1; echo "<table>"; while ($rowcount <= $totalrows) { echo "<tr>"; $sql = "SELECT * FROM ville_map WHERE id = '$rowcount'"; $sql_result = mysql_query($sql, $connection); while ($row = mysql_fetch_array($sql_result)) { $c1 = explode(',', $row["c1"]); $c2 = explode(',', $row["c2"]); $c3 = explode(',', $row["c3"]); $c4 = explode(',', $row["c4"]); $c5 = explode(',', $row["c5"]); while ($columncount <= $columns) { $arraynum = ${'c'.$columncount}; if ($arraynum[2] > 0) { $playerimage = '<img src="images/player' .$arraynum[2]. '.png"'; } else { $playerimage = ""; } echo '<td background="images/' .$arraynum[0]. '.jpg" width="50" height="50">' .$playerimage. '</td>' ; $columncount++; } } echo "</tr>"; $rowcount++; } ?> </table> any help would be much appreciated. Hey, I have the following code that gets the name of the course from the XML. XML Snippet Code: [Select] <?xml version="1.0"?> <courses> <course> <id>70</id> <name>Marketing and Social Media</name> <dates> <date> <instance_id>6747</instance_id> <location /> <course_type>Day</course_type> <date_available>2011/07/13</date_available> <time_start>9:30</time_start> <time_end>17:00</time_end> <availibility>7</availibility> <running_dates> <running_date>2011/07/13</running_date> <running_date>2011/07/14</running_date> </running_dates> </date> </dates> </course> <course> </courses> PHP Code: [Select] $dom = new DomDocument(); $dom->load("courses.xml"); $xp = new domxpath($dom); $titles = $xp->query("/courses/course/name"); foreach ($titles as $node) { print $node->textContent . " "; } This prints out the course name fine. My question is how Can i get the rest of the data from the same query. For example why cant I do something like.. Code: [Select] ... foreach ($titles as $node) { print $node->name. " "; print $node->time_start. " "; print $node->course_type. " "; etc.. } So I want to loop through get the name and assign the rest of the nodes in there to variables or something. i have some code which loops through a table, and displays the results. i have then added extra code so that it loops through another table, and prints out the reults, that are related to the first loop. so the page should look like menu submenu 1 submenu 2 submenu 3 menu 2 submenu 4 etc The problem is that the code only prints out the first row from the first loop and nothing else. <?php $list = "SELECT * FROM section_main"; $result = mysql_query($list) or die ("Query failed"); $numofrows = mysql_num_rows($result); echo "<table border='1' id='section_list'>"; echo "<tr><th>section_id</th><th>section_title</th></tr>"; for($j = 1; $j < $numofrows; $j++) { echo '<tr>'; $row = mysql_fetch_array($result); echo "<td>". $row['section_id'] . "</td><td>". $row['section_title'] . "</td>"; $query = "SELECT section_sub.section_sub_title, section_sub.section_title WHERE section_sub.section_title = " .$row['section_title']."ORDER BY section_sub_title"; $result2 = mysql_query($query) or die ("query failed2");//This part does not work $numofrows2 = mysql_num_rows($result2); for($i = 0; $i<$numofrows2; $i++){ $row2 = mysql_fetch_array($result2); echo '<tr>'.$row2['section_sub_title'].''; } } echo "</tr>"; echo '</table>'; ?> Any help on whats wrong would be great Hi all, I am trying to show information on a page if a value collected from a $_GET value is the same as a value in a Mysql database provided that the users email address links the email address next to the value in the mysql database. I have created the script however as there are more than one $row['value'] I can not get a foreach loop to work to scroll through all the $row['value'] values until it finds a matching one. Hope you can see from the code what I am talking about. The code I have is below: <?php $email = $_SESSION['logname']; $sql = "SELECT reg FROM sales WHERE email='$email'"; $result = mysqli_query($cxn,$sql) or die ("Couldn't execute query"); while($row = mysqli_fetch_assoc($result)) // NEED HELP INSERTING A FOREACH $ROW['REG'] SEE IF IT MATCHES $_GET['REG'] TYPE OF SCRIPT// { if ($row['reg'] == $_GET['reg'] ) { echo $row['reg'] . " is registered by you!"; } elseif ($row['reg'] != $_GET['reg'] ) { echo $_GET['reg'] . "<br>"; echo $row['reg']; echo $email . "<br>"; echo "I am sorry but the $_GET[reg] does not seem to be registered by you!"; exit(); } } ?> I have a website of grids of webcam images.
I have decided to make a looping webpage where I want just 1 image per page and every 2 seconds moves on to the next image.
I have the following code - but it only gets 1 image. I was going to update the database record with the next image but have decided it will be easier to get an array and loop round that somehow. Normally when I loop its easy to display the results in a table but this time i want it to display 1 image (record) at a time then move on...
The code below works fine (only showing the first image form the website in my database)
I hope someone can help me out please.
TIA
<html> <head> <title>My webcam page </title> </head> <?php $host = 'localhost'; $user = 'my_User'; $pass = 'my_Password'; $db = 'my_db'; $con = mysqli_connect($host, $user, $pass, $db) or die(mysqli_connect_error()); $sql = "SELECT * FROM `websites` WHERE `currentshowing`=1 LIMIT 0, 30 "; $result = mysqli_query($con,$sql); if (!$result) { die("Error: Data not found.."); } $test = mysqli_fetch_array($result); $webpic=$test['webpic']; $basesite=$test['basesite']; $location=$test['location']; ?> <div align="center"> <h1>MY WEBSITE (Ongoing work)</h1> </div> <td><div align="center"><?PHP echo $location; ?><br> <a href="<?PHP echo $basesite; ?>"> <img src="<?PHP echo $webpic; ?>" alt="<?PHP echo $location; ?>" width="80%" border="0"/> </a></div></td> </body> </html> Hello all. How would I loop through this array and find each "DTM" value? I want to be able to loop thru this array so that I can determine when to add 123, 456, ... 789, 1012 ... 123, 456 to a database. Hope this makes some sense... Thanks for any help on this one. Code: [Select] <?php $aryValues = array('DTM', '123', '456', 'DTM', '789', '1012', 'DTM', '123', '456'); ?> Ok I have this form with 6 fields that the user enters a geocaching code. In the database I have a table called cacheinfo. There are 6 enteries in the database in this table. Now Im trying to confirm that each field entered matches the right geo code. I have it working but I feel that its a very bad way of doing it my way. can someone please show me a better way as I have other situations I do something simliar and its just getting silly. Here is the code; if(isset($_POST['nextbtn'])){ $cache1 = trim($_POST['cache1']); $cache2 = trim($_POST['cache2']); $cache3 = trim($_POST['cache3']); $cache4 = trim($_POST['cache4']); $cache5 = trim($_POST['cache5']); $cache6 = trim($_POST['cache6']); $cache1 = mysql_real_escape_string($cache1); $cache2 = mysql_real_escape_string($cache2); $cache3 = mysql_real_escape_string($cache3); $cache4 = mysql_real_escape_string($cache4); $cache5 = mysql_real_escape_string($cache5); $cache6 = mysql_real_escape_string($cache6); $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='1'") or die('can not find cache information'); $cache1 = mysql_fetch_array($FetchCache); if($cache1 !==$cache1['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='2'") or die('can not find cache information'); $cache2 = mysql_fetch_array($FetchCache); if($cache2 !==$cache2['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='3'") or die('can not find cache information'); $cache3 = mysql_fetch_array($FetchCache); if($cache3 !==$cache3['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='4'") or die('can not find cache information'); $cache4 = mysql_fetch_array($FetchCache); if($cache4 !==$cache4['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='5'") or die('can not find cache information'); $cache5 = mysql_fetch_array($FetchCache); if($cache5 !==$cache5['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } $FetchCache = mysql_query("SELECT * FROM cacheInfo WHERE cacheInfoID='6'") or die('can not find cache information'); $cache6 = mysql_fetch_array($FetchCache); if($cache6 !==$cache6['cacheCode']){ $url = "/register-cache.php?error=true"; header("Location: $url"); } // If all match now run the rest of my code...... } I want to display 50 results, theirfore I'm using a while loop to do so, the issue is, if $row consists of results lower then 50 (it will display them) and not display 50..so I'm trying to figure out a way so even if $row doesn't cosist of 50 i'll display what it has aswell as continue the $i (and for the rest display NO CONTENT). I've come up with the following on the spot (not sure if it even would work) - but was wanting a better solution. $i = 0; $results = mysql_num_rows($result); while ($row = mysql_fetch_assoc($result)) { $i++; echo $i .' CONTENT '.$row['name'].'<br />'; } if ($result < 50) { for($i <= 50 - $result; $i++) { echo $i .' NO CONTENT<br />'; } } Hello All, I have two arrays. One called $number_array and one called $title_array. $number_array = (1,2,3,4); $title_array = ("Title One", "Title Two", "Title Three", "Title Four"); Now what I want to do is run through each of the arrays one by one each time I query my database, so for example the first time it would output the query and title as: Code: [Select] //First time SELECT * FROM tbl WHERE something = 1 <optgroup label="Title One"> //Second time SELECT * FROM tbl WHERE something = 2 <optgroup label="Title Two"> //etc.. so here's my code: <? echo '<select id="class" class="selectbox" name="class">'; $number_array = (1,2,3,4); $title_array = ("Title One", "Title Two", "Title Three", "Title Four"); $result = mysql_query ('SELECT * FROM tbl WHERE something = ".$number_array."') or die ('Error: '.mysql_error ()); echo '<optgroup label="".$title_array."">'; while ($row = mysql_fetch_array($result)) { echo '<option value="'.$row['id'].'" class="'.$row['name'].'">'.strtoupper($row['name']).'</option>'; } echo '</optgroup>'; echo ' </select>'; ?> Anyone please help? |