I am trying to write a program of photoalbums in simple PHP, but i want to make it a little more advanced then i used to do.
Usually i wrote it like this:
<?php $query = mysql_query("SELECT year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
$query2 = mysql_query("SELECT albumName, url FROM photo WHERE year = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "".$albumName."<br>";
}
} ?>
As you would understand it's really bad to have two while loops in one, so i want to do it differently. I want to learn how to do this better. The thing is, I don't know a name for this so it's difficult to search on this subject. Is there anyone able to hand me a snippet of code, a source or something to get me on the way?
Thank you so much.
You could do
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "".$album->albumName."<br>";
}
?>
What if you do this:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "".$albumName."<br>";
}
?>
What would be wrong?
Now your code might produce an album more than one times, if there are many albums per year.
Related
What I am trying to do is show a small widget on the home page to let a user know when their membership expires. Here is my current code
$subExpire = Engine_Api::_()->getDbtable('subscriptions', 'payment');
$db2 = $streamTable->getAdapter();
$stmt2 = $db2->query("select * from engine4_payment_subscriptions where `user_id`='$user_id'");
$arr2 = $stmt2->fetch();
if ($arr2['expiration_date']=="NULL")
{
$exp = "NEVER";
}
echo $exp;
I think the major issue has to do with Engine_Api::_()->getDbtable('subscriptions', 'payment');
Ultimately once it comes back with a date I would like to calculate how many days left in the membership from the current date.
Any suggestions?
PS, $user_id is defined and does return a numeric value
One more thing, the actual table name is engine4_payment_subscriptions
That´s a strange way of making the query in social engine, try this:
$table = Engine_Api::_()->getDbtable('subscriptions', 'payment');
$select = $table->select()->where('user_id = ?', $user_id);
$arr2 = $table->fetchAll($select);
if ($arr2['expiration_date']=="NULL")
{
$exp = "NEVER";
}
echo $exp;
I'm working on an online booking system, so I have a php script that receives a date and will output an array of possible timeslots that are free on that date. I'm trying to make it so that when closing the datepicker it sends the variables to the file and retrieves the result. At the moment the submit button also leads to the php file, and will show me available slots when I choose a date. The php part works, but when I add events to the datepicker it won't submit any variables to the php file. I think this is also the cause that when I add another load.('input_date.php'); I get the full timeslot list caused by the if(isset... Can anyone tell me why jQuery is ruining my variable posting? Thanks in advance..
$(document).ready(function() {
$("#dates").load('input_date.php');
$("#datepicker").datepicker({onClose: function() {
$.post("input_date.php", $('#datepicker').serialize());
alert(1);
}});
});
This is the php file:
<?php
include('connection.php');
error_reporting(0);
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
if(isset($treatment) && isset($bookdate)){
$exp = explode("-", $bookdate);
//determine what day of the week it is
$timestamp = mktime(0,0,0,$exp[1],$exp[0],$exp[2]);
$dw = date( "w", $timestamp); // sun0,mon1,tue2,wed3,thur4,fri5,sat6
echo $dw."weekday"; //week day
echo"<br/>";
//find bookings with same date
$q = mysql_query("SELECT BOOK_SLOT_ID FROM BOOKINGS WHERE BOOK_DATE='$bookdate'");
//make array of booking slots
$array1 = array();
while ($s = mysql_fetch_array($q)) {
$array1[] = $s['BOOK_SLOT_ID'];
}
$q2 = mysql_query("SELECT SL_ID FROM SLOTS");
//make array of all slots
$array2 = array();
while ($s2 = mysql_fetch_array($q2)) {
$array2[] = $s2['SL_ID'];
}
//remove bookings from all slots
$arr_res = array_diff($array2, $array1);
//make selectable options of results
echo "<SELECT>";
foreach($arr_res as $op){
$r = mysql_query("SELECT SL_TIME FROM SLOTS WHERE SL_ID='$op'");
$q3 = mysql_fetch_array($r);
echo "<OPTION value=".$op.">".$q3['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}else{
$else = mysql_query("SELECT * FROM SLOTS");
echo "<SELECT>";
while($array_else = mysql_fetch_array($else)){
echo "<OPTION value=".$array_else['SL_ID'].">".$array_else['SL_TIME']."</OPTION>";
}
echo "</SELECT>";
}
?>
I believe it is because you have this line of code:
$('#datepicker').serialize()
This should be changed to the id of the form not the datapicker. In your PHP you are trying to get two seperate values:
$treatment = $_POST['treatment'];
$bookdate = $_POST['bookdate'];
Right now you are just sending the value of the input field #datepicker.
My code below basically gets a bunch of films from the db and sets the year as the array key then echoes out each film per year. Thats all cool although my results are getting to long and need paginating. I cant find any examples that help my situation as most pagination in php is for while loops - appreciate any help or feedback.
I dont mind if its jquery or php or a combo of both.
<?php
require_once('Connections/timeline.php');
mysql_select_db($database_timeline, $timeline);
// select all the events from the database ordered by date:
$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC");
$filmArray = null;
while($row_res = mysql_fetch_assoc($res)) {
$year = $row_res['year'];
$filmArray[$year][] = $row_res;
}
//for each year in the film array echo out each film within that year
foreach($filmArray as $year => $films) {
echo $year;
echo '<br />';
foreach($films as $film) {
echo $film['event'];
echo '<br />';
echo $film['name'];
echo '<br />';
}
}
?>
You need to have GET parameter, for example, page.
URL: localhost/film.php?page=1
And then
if (isset($_GET['page']))
$page = $_GET['page'];
else
$page = 1;
$entriesPerPage = 20;
$limitFrom = $page - 1;
$limitTill = $limitFrom + $entriesPerPage;
And then Your SQL query:
$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC LIMIT $limitFrom, $limitTill");
And in the end, create html links.
Previous
Next
This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>
I will try to be as clear as possible because I can't get anybody to help me around,
I am trying to associate some data from a 'videos' table with their respective ID.
Lets say, I have column ID, title, serie, season, episode.
I am getting my data :
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
?>
(that is in the page where you see the video itself)
So now I can get the number of episodes from a serie and season.
What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/
So how can I get the ID of the following and previous episodes of the same season AND serie?
Help will be much appreciated!
The easiest thing I thought of is
<?=$row['id'] + 1?>
<?=$row['id'] - 1?>
But the thing is that it's mixed videos, so it wont work 100%
I think you've taken my example too literally. I'll post a complete example in the morning (I'm just replying from my iPhone at the mo). For some reason it wouldn't let me add a comment to your last reply, so sorry this is as an answer.
[edit] here's a more complete example:
<?php
$result = mysql_query("SELECT * FROM videos WHERE series='$series' AND season = '$season'");
$last_row = null;
$next_row = null;
$current_id = $_GET['id'];
while($row = mysql_fetch_assoc($result)) {
if($current_id == $row['id']) {
$next_row = mysql_fetch_assoc($result);
break;
}
$last_row = $row;
}
if($last_row != null) {
echo "<a href='?id={$last_row['id']}'>Prev</><br/>\n";
}
if($next_row != null) {
echo "<a href='?id={$next_row['id']}'>Next</><br/>\n";
}
?>
A few things to note:
This is untested.
In your initial example, I didn't know where you were getting the $row['serie'] and $row['season'], so in my example, I've just used the variables $series and $season. You'll have to fill these in with what you want the current result set to be filtered by.
For my example, the URL format uses the GET layout (ie. ?id=).
If you do:
$results = mysql_query($sql);
(where $sql is your mentioned select statement)
Then the $results array will contain all results of that series/season.
So you can access it via:
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
Note that you'll of course need to check that $n - 1 isn't less than zero, and ($n + 1) isn't greater than your $total_rows.
Here is what I tried, I guess it is what you meant,
All that it's doing is put the previous episode, so I get /view/id/3/ (if the episode i am watching is 4)
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
?>
<? if($row['episode'] == 1) { ?>
<td align="center" width="33%"></td>
<? } else { ?>
<td align="center" width="33%"><img src="images/previous.gif" srcover="images/previoush.gif" alt="Previous Video" border="0" /></td><? } ?>
That is only for the previous one,
Sorry I had to post like this, if not it wouldnt have appeared correctly,
(Correct me if I'm wrong with the code)
And thanks for the reply