Jump to content

DavidAM

Staff Alumni
  • Posts

    1,984
  • Joined

  • Days Won

    10

Everything posted by DavidAM

  1. I think you need to look at the checked attribute of the checkbox rather than the value. function checkValue() { var linkemail=document.forms["theForm"]["linkemail"].checked if (linkemail) { document.getElementById('xtraInfo').style.display=''; } else { document.getElementById('xtraInfo').style.display='none'; } }
  2. As requinix said, $_POST["formcheck"] will be an array of the boxes checked. So in your processing code you could do something like this: if (isset($_POST["formcheck"])) { foreach($_POST["formcheck"] as $choice) { // At this point, $choice will be A or B or C // So do what you want with it } } else { // None of the boxes was checked }
  3. So you want to call variation(1); pause a while call variation(2); pause a while call variation(3); pause a while and so forth? You would need to make the variable i static so it will maintain its value when the function exits. Like I said, I'm no JS expert, but I would do something like this: var i = 1; function variationTimer(){ variation(i); i++; if (i>=3){ i = 1; } setTimeout("variationTimer()",6000); } // Kickoff the timer variationTimer();
  4. function variationTimer(){ for(i=1;i<4;i++){ variation(i); i++; if (i>=3){ i = 1; } setTimeout("variationTimer()",6000); } } This function is running an infinite FOR loop which is calling setTimeout ON EVERY PASS THROUGH THE LOOP. In very short order you have set hundreds of timers. And as those timers fire, they are each starting ANOTHER infinite FOR loop and setting more timers, which are starting more infinite FOR loops and setting more timers, which are starting more infinite FOR loops and setting more timers, which are starting more infinite FOR loops and setting more timers --- ad infinitum Well, I think that's the case. I'm no JavaScript expert
  5. Order by the count: $query = "SELECT id, COUNT(*) as kb FROM part GROUP BY id ORDER BY COUNT(*) DESC"; or since you aliased the count as 'kb': $query = "SELECT id, COUNT(*) as kb FROM part GROUP BY id ORDER BY kb DESC"; * DESC indicates descending so the highest count will be the first row returned.
  6. Just a couple of comments before I answer your question. 1) I see no reason not to make the uid in the user_profiles table the PRIMARY KEY for that table. 2) Be aware, that innoDB is the only engine that supports Foreign Keys. If you run those create statements at a host that does NOT support innoDB, the server will use whatever the default engine is (probably myIsam) which will NOT define and will NOT enforce the foreign key constraints -- and will NOT, repeat NOT, issue any errors or warnings about them not being created (I found this out the hard way). So, if the engine is NOT innoDB, you will have to manually delete BOTH records as the foreign key CASCADE will not happen. On to your question. When a user visits their profile page, I would guess that you want to read their current values from the database and provide them as the default values on the form, so if they already have a profile, they do not have to enter everything every time they make a change. If you are doing this, it should be a simple matter to add a SESSION variable indicating they already have a profile. Then when they POST the form, you check this variable to determine if you should do an INSERT or UPDATE. That should save you an extra trip to the database. Another option is the use the Insert ... On Duplicate Key Update command. Although, as a (personal) rule, I stay away from it. It is a viable choice, and probably not much worse (performance wise) from doing the extra select.
  7. if (empty($row['mycount'])) { $row['mycount'] = '0'; } Should do the trick. If the element does not exist in the array, or if it is false, null, or zero; empty() will be true. You could also do it using the ternary operator in the output: echo 'The count is: ' . (empty($row['mycount']) ? '0' : $row['mycount']);
  8. First, your data definition shows: books-to-authors as many-to-many; books-to-subjects as many-to-many; books-to-publishers as many-to-one. I'm not sure I see why books-to-subjects is many-to-many, I generally think of a book as having a single subject, but I don't know how you are defining "subjects". To answer your questions: Yes, since there could be multiple Authors and/or Subjects, you will have to loop the result set of that query to present all of the data. No. Normalization is about storage and maintenance. If you normalize your data properly, you save storage space -- you only store the Title of a book in one place. And you reduce you maintenance overhead - if you need to correct the spelling of an Author's name, you edit it in one place only. Retrieval, will return multiple instances of the same book Title regardless of whether the data is properly normalized or not. Yes there is. You could do multiple queries, with queries inside a loop -- which most people on this forum will say "don't ever do". Or you could aggregate the data using the GROUP_CONCAT() function of mySql. It all depends on your presentation requirements. I think the outline you provided is normalized properly (other than using the wrong terminology for the relationships). Be aware that with two (or more) many-to-many relationships, the query you proposed will return a lot more rows than you think. Say there are three Authors and two subjects for a given book. You probably expect three or five rows, but you will, in fact, get six. Author1 will be linked with every subject (2 rows), Author2 will be linked with every subject (2 rows), and Author3 will be linked with every subject (2 rows) -- that's six rows with every author listed twice (once for each subject) and every subject listed three times (once for every author). Having the front-end process this result could be tedious and error prone. I would likely use multiple queries or aggregate the data at the server. As an example of aggregating the data, here is your proposed query, modified slightly: SELECT b.title, b.pages, p.publisher, GROUP_CONTCAT(s.subject SEPARATOR ', ') as Subj, GROUP_CONCAT(a.author SEPARATOR ', ') as Auth FROM books b INNER JOIN bookSubjects bs USING (bookID), INNER JOIN subjects s USING (subjectID) , INNER JOIN bookAuthors ba USING (bookID), INNER JOIN authors a USING (authorID), INNER JOIN publishers p USING (publisherID) WHERE b.bookID = 13 GROUP BY b.bookID; This will return a single row for the book, with multiple Authors in a comma-delimited field and multiple Subjects in a comma-delimited field. You could then manipulate the Subj and Auth fields in PHP to fit your presentation strategy. I have not tested this specific query, but I have found the function useful. See the manual for GROUP_CONCAT() for more details on this function.
  9. If the Log table's ID is referenced from any other table (making it a foreign key in the other table), be sure you change the definition there as well. Foreign Keys should have the same data type definition (size and signed/unsigned) as the primary key that they are referring to.
  10. Interesting, I always wondered what the symptoms were when you run out of auto_increment values. You defined the ID as tinyint, which is a one-byte integer. Since you did not specify UNSIGNED, that column can range from -128 to +127. So you can not increment the value for a new row, since that would cause the ID value to overflow. Since AUTO_INCREMENT columns should never be negative, you should always define auto_increment columns as UNSIGNED. An unsigned tinyint can range from 0 to 255. However, the server starts auto_increment columns at 1, so you can store 255 rows with a tinyint ID, if you switch it to unsigned. Note: Before you ask, the (4) in the datatype (tinyint(4)) is the number of DISPLAY columns the server will use when you select the value. It has nothing to do with how large of an integer you can enter into the field. I really think this is a dumb design, but hey, they didn't ask me.
  11. I copied that code to a new script file, put in my email address for TO and FROM. And ran it. The message was not displayed in the browser (except for the "Registration email has been sent" message that you echo at the end) and the email I received contained the text from your script - including the image (which is pretty cool). In other words, that code works exactly as you want it to, for me.
  12. $headers ="MIME-Version: 1.0rn"; $headers .= "Content-type : text/html; charset=iso=8859-1rn"; That should be \r\n on the end of those lines, not rn
  13. You could use the CC header or the TO address if you want a copy to go to your mailbox AND you don't mind everyone getting that address. The CC values are shown to everyone as well as the TO. You can use something like this to set the BCC header: $emailAddr = array('[email protected]', '[email protected]', '[email protected]', '[email protected]'); /* Leave this blank or put your own address in here EVERYONE WHO RECEIVES THIS MESSAGE WILL SEE THIS ADDRESS */ $msgTo = ''; $msgSubj = 'Hello World'; $msgBody = 'This is a test message with BCC'; $msgHdrs = "From: [email protected]\r\n"; $msgHdrs .= 'Bcc: ' . implode(', ', $emailAddr) . "\r\n\r\n"; if (mail($msgTo, $msgSubj, $msgBody, $msgHdrs)) { echo 'Mail Sent'; } else { echo 'Mail Failed'; } I have no idea if there is a limit on the number of addresses or length of the header. I imagine that at some point, the mail program is going to balk if there are too many addresses there.
  14. First, you are putting all of the email addresses into the TO field of a single email message. This might work, depending on your mail server. However, this means that ALL of your customers and sponsors will have EVERYBODY'S email address. I don't know if you want this or not but IF I was a customer, I would NOT want someone sending my email address to ALL of their customers. Now, on to the problem. You stated that there are two fields in the text file, but your code is treating each line as if it was a single field. You need to split the name and email apart and use each field for its intended purpose: // Example Code, this probably will not work as written $email_list = file("elist.txt"); foreach ($email_list as $line) { list($name, $email) = explode('|', trim($line)); $message = 'Hello, ' . $name; mail($email,$subject,$message,$headers) } Of course, if you want to do it in a single call to mail(), and your mail server will handle however many addresses you provide, you can do it. BUT I would recommend NOT putting them in the TO field; use the BCC header, instead.
  15. You have the parameters backwards. The query comes first, and the connection comes second.
  16. Look carefully at your query. You have aliased the PSEUDO TABLE as "x" NOT the MAX(pokemon_pos) value. SELECT MAX(pokemon_pos) FROM ( ... ) AS x probably needs to be: SELECT MAX(pokemon_pos) AS x FROM ( ... ) AS PT (I put PT as the table alias because, I believe, mySql requires all pseudo-tables to have an alias).
  17. First the easy stuff: 1) You might want to add ".mp3" to the title assignment: $title = $row['title'] . '.mp3'; - you were doing that in your original code. 2) use shuffle($songs); to randomly rearrange the elements of the array. $songs = array('01.mp3', '02.mp3', '03.mp3', '04.mp3', '05.mp3', '06.mp3', '07.mp3', '08.mp3', '09.mp3', '10.mp3'); shuffle($songs); 3) use a foreach loop to walk the array and output the results: foreach ($playlist as $title) { echo $title . '<BR />'; } On the missing commercials: It appears that the first two priority/failovers are not returning anything. In the last code you posted, we had: $priorities = array( array(4, 3), array(3), array(4, 2, 3), array(4, 1) ); So if the first two are finding nothing and the last two are finding songs; that would indicate that there are no 4's or 3' being found (unless you changed the order or values of this array). Array ( [0] => 01.mp3 [1] => // array(4, 3) [2] => 02.mp3 [3] => // array(3) [4] => 03.mp3 [5] => cencfish // array(4, 2, 3) [6] => 04.mp3 [7] => cenccha // array(4, 1) [8] => 05.mp3 [9] => // array(4, 3) [10] => 06.mp3 [11] => // array(3) [12] => 07.mp3 [13] => cencglv1 // array(4, 2, 3) [14] => 08.mp3 [15] => cencfuel // array(4, 1) [16] => 09.mp3 [17] => // array(4, 3) [18] => 10.mp3 [19] => // array(3) ) Have a look at the data in the database, especially the 4's and 3's. Something is preventing them from being returned.
  18. HOLD THE PRESSES: There seems to be a line of code missing in the function. We need to assign the value from the query to the $title variable: $title = false; $rs = mysql_query($sql); // Change this IF and show any error if ($rs === false) { echo "Query Failed: $sql <BR />" . mysql_error(); } else { // we only want one row, so no while loop if ($row = mysql_fetch_assoc($rs)) { $id = $row['row_number']; // SOMEHOW THIS LINE GOT LOST $title = $row['title']; // THAT ONE JUST ABOVE HERE $sqlUp = "UPDATE audio SET last_play = NOW() WHERE row_number = $id"; if (! mysql_query($sqlUp)) { echo "Update Failed: $sql <BR />" . mysql_error(); } } } return $title;
  19. Yeah, it looks OK to me, too. SELECT row_number, title, CASE `priority` WHEN 4 THEN 0 WHEN 3 THEN 1 END AS priSort FROM audio WHERE `client_id` = '4' AND (`start_date` <= '2011-04-07' AND `end_date` >= '2011-04-07') AND `Thursday` = '1' AND `is_active` = '1' AND (`start_hour` <= '12' AND `end_hour` >= '12') AND `priority` IN (4,3) AND DATE(last_play) < DATE_SUB(NOW(), INTERVAL 10 MINUTE) ORDER BY priSort, last_play LIMIT 1 Questions: AND (`start_date` <= '2011-04-07' AND `end_date` >= '2011-04-07') are start_date and end_date actually defined with the DATE or DATETIME datatype? If not, they should be. You actually have columns named after the days of the week? I think you would get an sql error if not, but I may as well ask. AND (`start_hour` <= '12' AND `end_hour` >= '12') start_hour and end_hour have the INTEGER datatype? AND DATE(last_play) < DATE_SUB(NOW(), INTERVAL 10 MINUTE) last_play has the DATETIME data type? Are you sure there is data in the database that satisfies ALL of those requirements? Can you run this directly against your database, using mySqlAdmin or something to see what happens. Maybe pull the AND's out one at a time until you find the one that is breaking it? priSort (a long-winded explanation) You stated a while back that you wanted specific priorities with specific failovers if the requested priority was not available. So I build this array of priority requests with failovers (oops, I got the second and third ones swapped, but hopefully, you'll understand it well enough to make adjustments as needed). $priorities = array( array(4, 3), // Get a priority 4. If not available, get a priority 3 array(3), // Get a priority 3 (will always exist) array(4, 2, 3), // Get a priority 4. If not available, get a priority 2 // I added priority 3 here to show we could use more than one // failover - so, if priority 2 is not available get a priority 3 array(4, 1) // Get a priority 4. If not available, get a priority 1 ); While walking the list of songs, we use the $priInd to walk this list of priorities. We increment the index ($priInd++) - the postfix ++ (after the $priInd) means use the current value and then increment (by one). We then test to see if $priInd has reached the end of the $priorities list, and if so, we set it to zero (back to the beginning of the list). So we are passing one of the four priority/failover arrays to the getCommercial function. The first time this function is called, $priorities INSIDE THE FUNCTION will be an array containing 4 and 3. The second time, it is an array with one element which is 3. The third time, it is 4, 2, and 3. Next it gets 4 and 1. Then the next time, we have restarted the list, so it gets 4 and 3 again. We do two things with this array. We use it to build the IN phrase to restrict the SELECT to just those priorities. This is done with the implode() function. You see that in the query you pasted here as AND `priority` IN (4,3). The other thing we do is build a CASE statement so we can sort the values we get back. Why? We wanted to do this with a single query, so we used the IN phrase to SELECT multiple priorities. But we need those priorities in a specific order. Well, based on your requirements, we could have just sorted on priority DESCENDING and we would always get the higher priority first. But I tend to try and make the code as generic as possible. In the array -- array(4,3) -- the first element has index 0 (zero) and the second element has index 1 (one). So we write this case statement: CASE `priority` WHEN 4 THEN 0 WHEN 3 THEN 1 END AS priSort which says, (for each row that we retrieve) if the priority is 4 return the value 0 (zero), if the priority is 3, return the value 1 (one) -- we limited the query to 4 and 3, so we don't need to worry about anything else. So, we are returning a new column "AS priSort" with either a 0 or a 1 value. The "AS priSort" is just giving this new column a name so we can refer to it, it's called an ALIAS. Fortunately, mySql lets us use aliases in the ORDER BY. So we ORDER BY priSort. Since 0 comes before 1 (the values assigned to priSort), then the 4's will come BEFORE the 3's (in this case). If there are no 4's, then we only get 3's, so we can just use the first row returned. The beauty of this arrangement is that we can define a priority/failover of array(2, 4, 1, 3) and get the rows back in that order -- any 2's that exist will be first, then any 4's that exist, then any 1's that exist, then any 3's. I hope that clears it up a bit. I know its complex, but it is an elegant (if I may say so) single-query solution to the problem.
  20. Yeah, variables defined OUTSIDE of a function are not available INSIDE the function unless you pass them as parameters. We can add the $dow and $now and $hour to the function parameter list once we get things working. Or if you are taking them straight from the current date, we can use the appropriate SQL functions. But let's see what's wrong with the query first. If you didn't get any "Query Failed" messages, then it would appear that the query is not returning any rows. So let's take a look at the query: $sql = "SELECT row_number, title, $priCASE FROM audio WHERE `client_id` = '$client' AND (`start_date` <= '$now' AND `end_date` >= '$now') AND `$dow` = '1' AND `is_active` = '1' AND (`start_hour` <= '$hour' AND `end_hour` >= '$hour') AND `priority` IN ($priIN) AND DATE(last_play) < DATE_SUB(NOW(), INTERVAL 10 MINUTE) ORDER BY priSort, last_play LIMIT 1"; echo $sql . '<BR />'; Are you sure you have data in the database that matches the criteria? Add that echo statement so we can see the query (you'll take it out when we get it working). You can copy the query and run it directly against the database to see if you get anything. Post it here and I'll take a look. I wondered if I had setup that CASE statement correctly, but it sounds like you didn't get any error messages about the query. I added the condition for DATE(last_play) < 10 minutes ago. We might want to take that out, at least until we get it working. Multiple test runs, one after the other, can likely happen in less than 10 minutes and you might exclude everything. Since we order by last_play, we're going to get the oldest one anyway - except that the sort is within the priority, so higher priorities will repeat more often. That is, if you only have 1 priority 4, it will come up every time you ask for a priority 4 and never fail over; with the 10 minute limit in there, you would not be repeating the same commercial after every song.
  21. Looks like all of the even numbers in the array (which should be the commercials) are blank. Actually, they are probably false, which means the getCommercial() function failed to find anything. Do you have error reporting turned on? And did you get any errors? Not related to the problem, but since you put in your song titles, you can take out the for loop immediately below it. so the start of the that script would look like: // Turn on error reporting for development error_reporting(E_ALL); ini_set('display_errors', 1); // ** CREATE SOME DUMMY DATA FOR TESTING // Just fill the "songs" array with 10 songs $songs = array('01.mp3', '02.mp3', '03.mp3', '04.mp3', '05.mp3', '06.mp3', '07.mp3', '08.mp3', '09.mp3', '10.mp3'); /* WE DON'T NEED THIS FOR LOOP ANYMORE for ($i = 1; $i <= 10; $i++) { $songs[] = 'Song ' . $i; } */ To find out why the query is failing, we need to change the function just a little. Where we execute the query, change the IF statement and output the query and mysql_error() message: // Return false if we don't find anything at all $title = false; $rs = mysql_query($sql); // Change this IF and show any error if ($rs === false) { echo "Query Failed: $sql <BR />" . mysql_error(); } else { // we only want one row, so no while loop if ($row = mysql_fetch_assoc($rs)) { we might as well add a check on the UPDATE statement too, just to be sure: $sqlUp = "UPDATE audio SET last_play = NOW() WHERE row_number = $id"; if (! mysql_query($sqlUp)) { echo "Update Failed: $sql <BR />" . mysql_error(); }
  22. The error indicates it is a call to mysql_real_escape_string() that is causing the error. This function requires a connection to the database. The mysql_* functions will use the last connection that was established if one is not specified. And if there have been no connections, they will try to connect as the current user with no password. Take a look at your mysql_real_escape_string() calls. The error message says LINE 25, so start there and look above and below it. It looks like your method name is escapeString() it looks like that call, two lines above the mysql_query() call, is failing, causing the UPDATE query to embed some garbage data which is causing that last error message.
  23. I was kind of bored, so I knocked this out for you. I think it satisfies the requirements as stated. I did not run it to test, and some of the column names in the queries may be off, but I think you can fix that. Post back if you have any questions. I tried to document it with comments, so it should be understandable. (Famous last words, right ) I've made some assumptions: [*]The audio table has a unique numeric identifier which I have called ID [*]The priority column is numeric [*]There is a last_played column and it has the datetime datatype [*]You have already sanitized all of the inputs [*]I did not include some error checking that should probably be added: for instance, the getCommercial() function returns false if it can't find anything, the calling code does not check for this // ** CREATE SOME DUMMY DATA FOR TESTING // Just fill the "songs" array with 10 songs $songs = array(); for ($i = 1; $i <= 10; $i++) { $songs[] = 'Song ' . $i; } // values for other variables needed $client = 8; $dow = 1; // ** END DUMMY DATA FOR TESTING /* array of the priority we want, and the fail-over priorities (in order of prefernce) if what we want is not available NOTE: the way the getCommercial() function is written, you could extend each nested array, to multiple failovers (as I did with the third one) You could also provide a single value (as in the second array here) if you are sure it will exist. */ $priorities = array( array(4, 3), array(3), array(4, 2, 3), array(4, 1) ); // collect the songs/commercials in an array to output later $playlist = array(); // walk the song list and merge in commercials /* NOTE: We carry an index into the priorities array because we will cycle through it multiple times. */ $priInd = 0; $priCnt = count($priorities); foreach ($songs as $title) { $playlist[] = $title; $playlist[] = getCommercial($client, $dow, $priorities[$priInd++]); if ($priInd >= $priCnt) $priInd = 0; } print_r($playlist); // ** DONE ** // // ** FUNCTOINS ** // /* Get a commercial from the database. $priority is an array - the first element is the priority we want; the remaining elements is/are the priority we will take if the priority we want is not available (in order of preference). We build a CASE statement to generate a sort order based on the order in this array */ function getCommercial($client, $dow, $priorities) { // Calculate the date and hour (or pass them in as parameters) $nownohour = date('Y-m-d'); // or whatever $hournozero = date('h'); // or whatever /* convert the priorities array to a comma-separated list for the IN phrase and a CASE statement for the sort order */ $priIN = implode(',', $priorities); $priCASE = 'CASE `priority` '; foreach ($priorities as $key => $value) { $priCASE .= ' WHEN ' . $value . ' THEN ' . $key; } $priCASE .= ' END AS priSort'; // NOTE: we capture the unique ID of the song for the update // NOTE: I added a condition to exclude any commercials played in the last 10 minutes $sql = "SELECT ID, title, $priCASE FROM audio WHERE `client_id` = '$client' AND (`start_date` <= '$nownohour' AND `end_date` >= '$nownohour') AND `$dow` = '1' AND `is_active` = '1' AND (`start_hour` <= '$hournozero' AND `end_hour` >= '$hournozero') AND `priority` IN ($priIN) AND DATE(last_played) < DATE_SUB(NOW(), INTERVAL 10 MINUTE) ORDER BY priSort, last_played LIMIT 1"; // Return false if we don't find anything at all $title = false; $rs = mysql_query($sql); if (! $rs === false) { // we only want one row, so no while loop if ($row = mysql_fetch_assoc($rs)) { $id = $row['ID']; $title = $row['title']; $sqlUp = "UPDATE audio SET last_played = NOW() WHERE ID = $id"; mysql_query($sqlUp); } } return $title; } The tricky part is the priorities. We create a multi-dimensional array of priorities and fail-overs, in the order that we want to request them. We pass the elements (which are, themselves, arrays) in to getCommercial() in sequence. In the function we build an IN phrase (i.e. AND priority IN (4, 3)) to select the ones we want and we build a CASE statement for the sort order (i.e. CASE priority WHEN 4 THEN 0 WHEN 3 THEN 1 END AS priSort ... ORDER BY priSort) -- So the query will find priority 4's and 3's that satisfy the parameters and then return the 4's first, then the 3's. But we put a LIMIT of 1 on the query, so we will get the first row (which will be a 4 if one was found).
  24. I thought there might be more to it. So if I understand, you want to mix one-to-one your, let's call them "sponsored", songs with your database songs. One from the database, one from the sponsor list, one from the database, one from the sponsor list, etc.; until all of the sponsored songs are played. I have a couple of questions: 1) The example you gave will always play priority 4 songs if there are a significant number of them in the database. Even if you limit the query to songs NOT played today, if there are enough priority 4 songs, it will never fail over to priority 3, 2, or 1. Is this correct, or does your example need to extend into the other levels (i.e. 4 or 3, S, 4 or 2, S, 3, S, 4 or 1, S, 3 or 2, S, 2, S, 3 or 1, S, 2 or 1, S, 1)? Or do you just want it MORE likely that a priority 4 will play? 2) The query from your original post does nothing to randomize the songs. It will likely return the same songs in the same order when run at the same time of the same DOW. Even if we exclude songs by the last_played date, the order will be the same in a week or two. In fact, the query in the function I suggested, will likely return the same song every time it is called for level 4. 3) Your example shows all priority 4 songs played BEFORE any priority 3 songs. I guess that is what "priority" means, but do you really want it that way? Or do you want to randomly mix the songs in the list without regard to priority as long as there are more higher priority songs than lower? There are a couple of ways to tackle this, we just need to be sure of the requirements so we don't paint ourselves into a corner. We can tackle the UPDATE once we figure out the SELECT.
  25. Since you have the two query processes separated, there is no need to use different variable names (by adding the '2' to it) for each group. Unless you are going to refer to $sql, $rs, or $row later in the code (and I see no need to), there will be do conflict. There's a minor difference between the two SQL statements. From looking at it, I'm guessing this was a typo. If that is true, then this would be an excellent candidate for a function. function getTitle($client, $dow, $priority, $limit) { // Calculate the date and hour (or pass them in as parameters) $nownohour = date('Y-m-d'); // or whatever $hournozero = date('h'); // or whatever $sql = "SELECT * FROM audio WHERE `client_id` = '$client' AND (`start_date` <= '$nownohour' AND `end_date` >= '$nownohour') AND `$dow` = '1' AND `is_active` = '1' AND (`start_hour` <= '$hournozero' AND `end_hour` >= '$hournozero') AND `priority` = '$priority' LIMIT $limit"; $rs = mysql_query($sql); $matches = 0; while ($row = mysql_fetch_assoc($rs)) { $matches++; echo "$row[title].mp3<br />"; } return $matches; } Note: You have "LIMIT 1" in your queries, which means you will not get more than one row returned. In this case, the "while" loop is completely unnecessary, I left it in since I made the limit a parameter. Note: I highly recommend NOT using "SELECT *" as it sends ALL of the data from each selected row back to the client. Generally, you should only select the columns that you are going to need. Now you can call the function in a loop like this: for ($priority = 4; $priority > 0; $priority--) { if (getTitle($client, $dow, $priority, 1) > 0) break; } The "break" will cause the loop to exit as soon as the function returns some value greater than zero (i.e. it found a title). Change the "$priority > 0" to "$priority >= 0" if you actually have a priority zero in your database Disclaimer: This code is untested and provided as educational material only. There is no warranty, expressed or implied on the usability, fitness, correctness, or prettiness of the provided code.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.