PHP - Moved: Having A Query Within A Loop
This topic has been moved to MySQL Help.
http://www.phpfreaks.com/forums/index.php?topic=306079.0 Similar TutorialsHi Could do with some help. I have 20 clients (client-1, client-2, client-3) and so on. Each client makes several calls per day. How can I get a row count from two columns (Date, clid) and echo the count for each client? I am in the process of making a stream page where users can enter a status, like and comment others statuses, like on facebook.
I have 4 tables, stream, users, likes and comments as shown below, with the rows I will be using:
stream stream_status Basically, this part of the code is checking the "scanned" table in my mysql database to get the last scanned date for the item at hand. It then takes that date and selects all the vendor items in the odbc table "ARVEND" that are greater than the last purchase date. || This is where I am running into a problem. When it loops through each vendor item it selects from the "associated" mysql table to see if the vendor item has been scanned. If it does not find anything I am trying to get the $checkpurdate variable to add 1 to itself. | In the second script you will see the elseif($checkpurdate>0) .... Here I am saying if there are any vendor items that have not been scanned, highlight the row in yellow. But, this part of my code $checkpurdate = $checkpurdate + 1; does not seem to be counting correctly. Sometimes it counts '4' for an item when there are only two vendor items available. All of this may sound confusing since you may not know what I am trying to do. But, the main problem I am having is the counting part is returning wrong numbers. $checkpurdate = $checkpurdate + 1; Code: [Select] /* $checkpurdate */ $query3 = "SELECT date FROM scanned WHERE `item` = '$ITEM' ORDER BY date DESC LIMIT 1"; $result3 = mysql_query($query3); $checklastdate = ""; while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {$checklastdate= $row3['date']; $checklastdate=date("m/d/y", strtotime($checklastdate)); } //checkpurdate loops $checkassoc="0"; $checkpurdate="0"; $sqlc="SELECT RECNO5 FROM ARVEND WHERE PURDATE1 > '$checklastdate' AND ITEM = '$ITEM'"; $rsc=odbc_exec($conn,$sqlc); if (!$rsc) {exit("Error in SQL");} while (odbc_fetch_row($rsc)) { $checkrecno5=odbc_result($rsc,"RECNO5"); $checkassosquery = "associated WHERE `VENDORID` = '$checkrecno5' AND ITEM = '$ITEM'"; $checkassoc = get_rows($checkassosquery); if($checkassoc>0) { // do nothing } else { $checkpurdate = $checkpurdate + 1; } } Code: [Select] elseif($checkpurdate>0) { echo"<TR class=\"NV\"> <TD>"; } So I output the Threads for my forum onto the main screen like so <div class ='grid-container'> <?php //Get the Threads and output them onto the screen in a grid container $query = mysqli_query($conn, "SELECT * FROM Threads order by id desc") or die (mysqli_error($conn)); $GetPostsQuery = mysqli_query($conn, "SELECT Count(*) FROM Posts") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { $imageURL = 'upload/Thumbnails/'.rawurlencode($row["filename"]); $PostBody = nl2br($row['ThreadBody']); echo " <div class ='grid-item'> <div class='ThreadComment'> Comments: <br> </div> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <h2><a href='viewthread.php?id={$row['id']}'> {$row['Title']} </a></h2> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <p>$PostBody </p> </div> \n"; } ?> However I don't keep the count of comments against the threads on my Threads table. I've attached a "describe" of both my comments (named Posts) and my Threads table (name Threads) I want to output the count of the comments against each Post in the above While loop To obtain the amount of comments against a thread I can get this from SQL by doing select count(IdOfThread) from Posts where id='169' ; But how would I access a query in SQL for the Posts table whilst it's already querying the Threads table? How would I implement this into the above while loop? Many thanks (and my db design maybe incorrect I'm very new )
What I am trying to do is query a database using a loop conditional and return the data but my code only repeats the first instance multiple times! My code is below, I have tried to use comments to explain what should be happeing! $rows = null; $q1 = "SELECT * FROM table"; $r1 = mysql_query($q1) or die(mysql_error()); $i = 1; while($i <= 5){ $start = (1000 * $i); $end = ($start + 1000); while($a1 = mysql_fetch_array($r1, MYSQL_ASSOC)){ /* query the database where 'start' is >= 1000 and where 'end' is <= 2000, this should loop so the next time is where 'start' >= 1000 * $i should be 1000 then 2000, 3000 etc... and where 'end' should be 2000, 3000, 4000 etc... */ if($a1['start'] >= $start && $a1['end'] <= $end){ $rows .= $a1['col1'].':'.$a1['col2']."\n"; } } echo nl2br(trim($rows.'<p>')); $i++; } /* The problem is that it always shows multiple instances of the first result only where start = 1000 and end = 2000 */ Any help would be much appreciated!! I've created a function getsub(). The idea is that this function contains a query that grabs records from the categories table, using the $row['cat_id'] that I pass to it from within an existing while ($row=mysql_fetch_assoc($res)) loop. Heres the function: function getsub($rowid,$catsort) { global $system, $LANGUAGES, $subres; $subquery = "SELECT * FROM webid_categories WHERE parent_id = " . $rowid . " " . $catsort; $subres = mysql_query($subquery); $system->check_mysql($subres, $subquery, __LINE__, __FILE__); return $subres; } And heres the code that calls this function and passes the $row['cat_id'] value to it: // prepare categories list for templates/template // Prepare categories sorting if ($system->SETTINGS['catsorting'] == 'alpha') { $catsorting = ' ORDER BY cat_name ASC'; } else { $catsorting = ' ORDER BY sub_counter DESC'; } $query = "SELECT cat_id FROM " . $DBPrefix . "categories WHERE parent_id = -1"; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); $query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . mysql_result($res, 0) . " " . $catsorting . " LIMIT " . $system->SETTINGS['catstoshow']; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); while ($row = mysql_fetch_assoc($res)) { $subcats = getsub($row['cat_id'],$catsorting); while($subrow = mysql_fetch_assoc($subcats){ $template->assign_block_vars('sublist', array( 'SID' => $subrow['cat_id'], 'SNAME' => $category_names[$getrow['cat_id']] )); } $template->assign_block_vars('cat_list', array( 'CATAUCNUM' => ($row['sub_counter'] != 0) ? '(' . $row['sub_counter'] . ')' : '', 'ID' => $row['cat_id'], 'IMAGE' => (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '', 'COLOUR' => (empty($row['cat_colour'])) ? '#FFFFFF' : $row['cat_colour'], 'NAME' => $category_names[$row['cat_id']] )); } then a .tpl file just references the {sublist.SID} and {sublist.SNAME} variables. BUT.... It ain't working. My page just goes blank. Any help would be massively appreciated. mysql_query("update pupils set record='running' where pid !='$testing[0]' Have a web page that displays a number of update forms depending on the amout of records that get returned from a mysql query, if query returns 4 records then the page will display 4 identical forms, the trouble i'm having is getting the each of the 4 forms to display a different record as at the moment they all show just first record of query. I have played around with loops but not getting anywhere which may be due to my limited knowledge code for page is below Code: [Select] <?php $numberofrow =mysql_num_rows($Recordset1); for($counter = 1;$counter<=$numberofrow;$counter++){ ?> <label for="hometeam2"></label> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <label for="hometeam"></label> <input name="fixid" type="text" id="fixid" value="<?php echo $row_Recordset1['FixtureID']; ?>" /> <input name="hometeam" type="text" id="hometeam2" value="<?php echo $row_Recordset1['hometeamname']; ?>" /> <label for="homescore"></label> <input name="homescore" type="text" id="homescore" value="<?php echo $row_Recordset1['homescore']; ?>" /> <label for="awayscore"></label> <label for="fixid"></label> <input name="awayscore" type="text" id="awayscore" value="<?php echo $row_Recordset1['awayscore']; ?>" /> <label for="awayteam"></label> <input name="awayteam" type="text" id="awayteam" value="<?php echo $row_Recordset1['awayteamname']; ?>" /> <input type="submit" name="update" id="update" value="Submit" /> <input type="hidden" name="MM_update" value="form1" /> Hi, Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have: $query1="SELECT UserID FROM Users where RefID='$userid'"; $result1=mysql_query($query1); while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5') { echo ($row[0]); echo " "; $sql2 = "SELECT * FROM Users WHERE RefID=$row[0]"; $sql2result = mysql_query($sql2); $sql2querynum = mysql_numrows($sql2result); } Problem is, for every value it echoes out, I get the following warning: mysql_numrows(): supplied argument is not a valid MySQL result resource Like I said, I'm a newbie to PHP to maybe I'm not even going about doing this the right way. Hoping someone can help to point me in the right direction. I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. I am trying to create 3 columns of data from a query. I have used this code before for 2 columns but and now wanting to use for three columns.
There are 5 records from a join query. The first two columns display the results, 2 results in the left column and 3 results in the center column. The right column displayw empyt text used in displaying the results, there is no data to populate and it seems to mimic the the number from the center, 3.
Here is the URL to see the problem
http://specialslocat...ignID=1IBu3992p
Here is the Code for the query and the 3 column results.
<?php $UN_URL = $_GET['un']; $mS_MGMTcampaignID_URL = $_GET['mS_MGMTcampaignID']; ?> <table width="944" border="1" align="center" cellpadding="0" cellspacing="0"> <?php $result = mysql_query( "SELECT * FROM manager_Specials_company_mgmt MSCM LEFT JOIN b2c_coupons B2CC ON (MSCM.mS_MGMT_id = B2CC.m_primeID )WHERE mS_MGMTcampaignID = '$mS_MGMTcampaignID_URL' ORDER BY mS_MGMT_m_company ASC" ); $num_results = mysql_num_rows($result); $numb_tb_rows= ceil($num_results/3) ?> <? if ( $numb_tb_rows > 0 ) { ?> <tr > <td colspan="4" valign="top" class="body_text_10_Center"><strong><?=$mS_campaignName_mS?> is proud to sponsor <?=$num_results?> <? if ( $num_results == 1 ) { ?> company:</strong> <? } elseif ( $num_results > 1 ) { ?> companies:</strong> <? } ?> </td> </tr> <tr class="body_text_10_Center"> <!-- Column 1 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #1 if($num_results>=1) { for($i=0; $i<$numb_tb_rows; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #1 } } ?> </td> <!-- Column 2 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #2 if($num_results>=2) { for($i=($numb_tb_rows); $i<$num_results; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #2 } } ?> </td> <!-- Column 3 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #3 if($num_results>=3) { for($i=($numb_tb_rows); $i<$num_results; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #3 } } ?> </td> </tr> <? } else { echo ""; } ?> </table>Thanks for any help in advance. Mike
$start = 0; 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 have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=354677.0 This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=346652.0 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=315341.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=310594.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=329559.0 |