PHP - Select Newest
hi, i want to select the 5 newest records from a table in the database. the date they were entered is in a column called post_time and this is a timestamp(000-00-00 00:00:00). how would i go about this?
Similar TutorialsHi I'm currently wondering how people check for latest records each time they refresh only the latest records display in another color. For example a chat. When people submit post and another user refresh their chat page the newest post always get highlighted. Does it work with sessions or how does it work?
Hi I have the following script to show images from a directory and make thumbs , but I would like to know how to sort the images from newest to oldest and how to implement it in this script
I'm a rookie at this...
Many Thanks in Advance!
<?php # SETTINGS $max_width = 800; $max_height = 600; $per_page = 10; $page = $_GET['page']; $has_previous = false; $has_next = false; function getPictures() { global $page, $per_page, $has_previous, $has_next; if ( $handle = opendir(".") ) { $lightbox = rand(); echo '<ul id="pictures">'; $count = 0; $skip = $page * $per_page; if ( $skip != 0 ) $has_previous = true; while ( $count < $skip && ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) $count++; } $count = 0; while ( $count < $per_page && ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) { // make the thumbs directory if it doesn't already exist if ( ! is_dir('thumbs') ) { mkdir('thumbs'); } // make a thumbnail if it doesn't already exist if ( ! file_exists('thumbs/'.$file) ) { makeThumb( $file, $type ); } // create a link to $file, add the thumbnail echo '<li><a href="' . $file . '">'; echo '<img src="thumbs/'.$file.'" alt="" /></a></li>'; $count++; echo substr($file,strlen($folder),strpos($file, '.')-strlen($folder)); } } echo '</ul>'; while ( ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) { $has_next = true; break; } } } } function getPictureType($file) { $split = explode('.', $file); $ext = $split[count($split) - 1]; if ( preg_match('/jpg|jpeg/i', $ext) ) { return 'jpg'; } else if ( preg_match('/png/i', $ext) ) { return 'png'; } else if ( preg_match('/gif/i', $ext) ) { return 'gif'; } else { return ''; } } function makeThumb( $file, $type ) { global $max_width, $max_height; if ( $type == 'jpg' ) { $src = imagecreatefromjpeg($file); } else if ( $type == 'png' ) { $src = imagecreatefrompng($file); } else if ( $type == 'gif' ) { $src = imagecreatefromgif($file); } if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) { $newW = $oldW * ($max_width / $oldH); $newH = $max_height; } else { $newW = $max_width; $newH = $oldH * ($max_height / $oldW); } $new = imagecreatetruecolor($newW, $newH); imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH); if ( $type == 'jpg' ) { imagejpeg($new, 'thumbs/'.$file); } else if ( $type == 'png' ) { imagepng($new, 'thumbs/'.$file); } else if ( $type == 'gif' ) { imagegif($new, 'thumbs/'.$file); } imagedestroy($new); imagedestroy($src); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UFT-8" /> <title>Pictures</title> <link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" /> <style type="text/css"> body { width:780px; margin:0 auto; } #pictures li { float:left; height:<?php echo ($max_height + 10); ?>px; list-style:none outside; width:<?php echo ($max_width + 10); ?>px; text-align:center; } img { border:0; outline:none; } .prev { float:left; } .next { float:right; } </style> </head> <body> <?php getPictures(); ?> <div style="clear:both"></div> <?php if ( $has_previous ) echo '<p class="prev"><a href="?page='.($page - 1).'">← Previous Page</a></p>'; if ( $has_next ) echo '<p class="next"><a href="?page='.($page + 1).'">Next Page →</a></p>'; ?> <div style="clear:both"></div> <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="js/lightbox.js"></script> </body> </html> Hi there, Before I begin, I want you all to know that I've been learning PHP for nearly a month now, so apologies for the poorly-written code that's going to follow. Two of my buddies and I are working on building a small website that allows us to play around with PHP and MySQL, since we work on an actual site that always in need of coding help. I tried searching for similar threads on this forum, but I couldn't find anything that answers my questions. I'm trying to accomplish a few things here. I have a form that allows us to add a record into a table (hunting consisting of the following columns: id, title, date, data, added_by. What I want to do is write a function that retrieves the newest record added to that table, call that function in a different file (it'll appear on the home page), and add a link to that record. If that sounds confusing, then this is what I want to do: 1. Retrieve last record added to the Hunters DB with a function. 2. Call that function in main.php, where it displays the record and format it like "Latest News: Title of the record" 3. I want to embed the link in the "Latest News: <Title of the record>", so it's clickable (this should be easy for me to do). But I need it to use the id (this is the primary key) column, which changes if a new record is added. Format: www.mysite.com/hunters.php?id=1 (the id value changes if a record with an ID 3 is added, so all I have to do is change the 1 to 3 in my browser to access that new record). This is what I wrote (functions.php): Code: [Select] function getNewHunterNews() { global $huntersdb; // Global that connects to the Hunters db $query = mysql_query( "SELECT `id`, `title` FROM `hunters_news` ORDER BY `id` DESC LIMIT 1", $huntersdb ); while ( $row = mysql_fetch_assoc( $query ) ) { $id = $row['id']; $title = $row['title']; } return $row; } In main.php (functions.php is included in this file): Code: [Select] <?php $huntnews = getNewHunterNews(); ?> <div id="news"> Latest News:<br /><br /> <span class="bolddark"><?php echo "<a href="\"/hunters.php?id={$huntnews['id']}\">" . $huntnews['title'] . "</a>"; ?></span> </div> I make the above changes, and my main page white screens. D: I know it isn't my function, because I've written simpler functions that are called in main.php, and those work. The white screen happens whenever I make the change above to main.php. What am I doing wrong? I'm fairly certain the change to main.php is causing problems, but I can't seem to point out what it is. Is there a different approach I can should take? I'm still in the learning process, so please guide me in the right direction. Additionally, if there any suggestions or constructive criticism you'd like to throw at me, please feel free. Every bit helps. Thanks in advance for your help! guys this function below posts the data into table and im also able to send a link in email with caregory name but the issue is getting the id to the particular post i got no isea how do i get that? Code: [Select] function insert($postData) { $postData['description'] = clean($postData['description']); if(!EmailExists($postData['email'])){ $sql = " INSERT INTO tbl_emails SET email = '".$postData['email']."', postersname = '".$postData['postersname']."', phone = '".$postData['phone']."' "; executeSql($sql); } if(empty($_FILES['image']["name"])){ $sql = " INSERT INTO tbl SET title = '".$postData['title']."', image = '', postersname = '".$postData['postersname']."', category = '".$postData['category']."', type = '".$postData['type']."', state = '".$postData['state']."', location = '".$postData['location']."', email = '".$postData['email']."', phone = '".$postData['phone']."', description = '".$postData['description']."', time = '".time()."' "; executeSql($sql); }else{ global $uploadPath; $remove_symbols = array('+', '=', '-', '{', '}', '$', '(', ')','&'); $removed_symbols = str_replace($remove_symbols, "_", $_FILES['image']['name']); $randomnum=rand(00000000,99999999); $imagepath = uploadFile($_FILES['image'], $uploadPath); $image = new SimpleImage(); $image->load($imagepath); $image->resize(250,280); $resize_rename = $uploadPath.$randomnum._.$removed_symbols; $image->save($resize_rename); unlink($imagepath); //delete the original file $sql = " INSERT INTO tbl SET title = '".$postData['title']."', image = '".$resize_rename."', postersname = '".$postData['postersname']."', category = '".$postData['category']."', type = '".$postData['type']."', state = '".$postData['state']."', location = '".$postData['ocation']."', email = '".$postData['email']."', phone = '".$postData['phone']."', description = '".$postData['description']."', time = '".time()."' "; executeSql($sql); } } I have a posting system worked out, as well as my database configured to my linking.. But as of right now, my posts are posted from oldest to newest, having users scroll down or go to the next page to see the most recent post.
How would I "flip" that around and make my posts start from newest to oldest by its date/time (Which is stored in the database)?
Thanks!
Here is what I am trying to accomplish: I have a students table with a studentID I also have a notes table and a sched table with studentID The sched table is working as planned where if the student is scheduled for more than one time he is displayed twice. However if there are multiple notes per student the student is display for each individual note where I would like only the most current note to be displayed Here is what the output is: 1- 10:30:00 - 10:50:00 student3 Three FST Teacher One Special1 One Writing Ratios 09/10 2- 10:30:00 - 10:50:00 student3 Three FST Teacher One Special1 One Needs to work on fractions and decimals 09/10 3- 13:00:00 - 14:00:00 student3 Three FST Teacher One Special1 One Writing Ratios 09/10 4- 13:00:00 - 14:00:00 student3 Three FST Teacher One Special1 One Needs to work on fractions and decimals 09/10 As you can see I have two notes and two schedule times for this student. what I want it to display is only line 1 & 3. which is the newest note in the system. Below is my code that I am using. Any help would be greatly appreciated. Code: [Select] <?php $result = mysql_query("SELECT * FROM students LEFT JOIN teachers ON students.teacherId = teachers.teacherId LEFT JOIN course ON students.courseId = course.courseId LEFT JOIN specialEd ON students.specialId = specialEd.specialId LEFT JOIN sched ON students.studentId = sched.studentId ORDER BY start "); echo "<table>"; while ($row = mysql_fetch_array($result)){ $id = "?id=" . $row['studentId']; echo "<tr>"; echo "<td>" . $row['start'] . " - " . $row['stop'] . "</td>"; echo "<td>" . "<a href='student.php$id'>" . $row['fName'] . " " . $row['lName'] . "</td>"; echo "<td>" . $row['courseName'] . "</td>"; echo "<td>" . $row['teachers_fName'] . " " . $row['teachers_lName'] . "</td>"; echo "<td>" . $row['special_fName'] . " " . $row['special_lName'] . "</td>"; echo "<td>" . $row['note'] . "</td>"; echo "<td>" . date("m/d", strtotime($row['started'])) . "</td>"; echo "</tr>"; } echo "</table>"; ?> hirealimo.com.au/code1.php this works as i want it: Quote SELECT * FROM price INNER JOIN vehicle USING (vehicleID) WHERE vehicle.passengers >= 1 AND price.townID = 1 AND price.eventID = 1 but apparelty selecting * is not a good thing???? but if I do this: Quote SELECT priceID, price FROM price INNER JOIN vehicle....etc it works but i lose the info from the vehicle table. but how do i make this work: Quote SELECT priceID, price, type, description, passengers FROM price INNER JOIN vehicle....etc so that i am specifiying which colums from which tables to query?? thanks I have 2 queries that I want to join together to make one row
Dear All, I wish to have 2 drop down boxes, Country Select Box and Locality Select Box. The locality select box will be affected by the value chosen in the country select box. All is working fine except that the locality select box is not being populated. I know that the problem is in the sql statement WHERE country_id='$co' because i am having an error that $co is an undefined variable. All the rest works fine because i have replaced the $co variable directly with a number (say 98) for a particular country id and it worked fine. In what way can i define this variable $co so that it is accepted by my sql statement? Thank you for your help in advance. MySQL Tables indicated below: CREATE TABLE countries( country_id INT(3) UNSIGNED NOT NULL AUTO_INCREMENT, country_name VARCHAR(30) NOT NULL, PRIMARY KEY(country_id), UNIQUE KEY(country_name), INDEX(country_id), INDEX(country_name)) ENGINE=MyISAM; CREATE TABLE localities( locality_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, country_id INT(3) UNSIGNED NOT NULL, locality_name VARCHAR(50), PRIMARY KEY (locality_id), INDEX (country_id), INDEX (locality_name)) ENGINE=MyISAM; Extract PHP script included below: // connect to database require_once(MYSQL); if(isset($_POST['submitted'])) { // trim the incoming data /* this line runs every element in $_POST through the trim() function, and assigns the returned result to the new $trimmed array */ $trimmed=array_map('trim',$_POST); // clean the data $co=mysqli_real_escape_string($dbc,$trimmed['country']); $lc=mysqli_real_escape_string($dbc,$trimmed['locality']); } ?> <form action="form.php" method="post"> <p>Country <select name="country"> <option>Select Country</option> <?php $q="SELECT country_id, country_name FROM countries"; $r=mysqli_query($dbc,$q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); while($row=mysqli_fetch_array($r)) { $country_id=$row[0]; $country_name=$row[1]; echo '<option value="' . $country_id . '"'; if(isset($trimmed['country']) && ($trimmed['country']==$country_id)) echo 'selected="selected"'; echo '>' . $country_name . '</option>\n'; } ?> </select> </p> <p>Locality <select name="locality"> <option>Select Locality</option> <?php $ql="SELECT locality_id, country_id, locality_name FROM localities WHERE country_id='$co' ORDER BY locality_name"; $rl=mysqli_query($dbc,$ql) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); while($row=mysqli_fetch_array($rl)) { $locality_id=$row[0]; $country_id=$row[1]; $locality_name=$row[2]; echo '<option value="' . $locality_id . '"'; if(isset($trimmed['locality']) && ($trimmed['locality']==$locality_id)) echo 'selected="selected"'; echo '>' . $locality_name . '</option>\n'; } // close database connection mysqli_close($dbc); ?> </select> </p> <p><input type="submit" name="submit" value="Submit" /></p> <input type="hidden" name="submitted" value="TRUE" /> </form> I'm using a PHP helpdesk script, but when a customer submits a ticket, they are able to assign a category. I want to be able to have the category function so I can move tickets around, but only allow customers to assign to one. (Basically I want to hide the Select Box on the new ticket page) This is the code which displays the select box: Quote <td style="text-align:right" width="150"><?php echo $hesklang['category']; ?>: <font class="important">*</font></td> <td width="80%"><select name="category"> Can you tell me what I can do to "hide" the category select box without getting rid of it? (The page requires a variable for category) Thanks Hi, I'm not quite sure how to do this, so i thought i'd ask you guys from some assistance. Basically i am inserting Author's into a table successfully using an array. The reason for this is that i have multiple authors being added and there is no limit as to how many. An example of what i mean can be seen he http://www.prima.cse.salford.ac.uk:8080/~ibrarhussain/test.html You can click on "Add author" to add however many necessary.. Anyway, i have got the insert working, however when i edit i want to be able to see all the authors that have been added but obviously i don't know how many there are.. Typically i would like to see something like this: http://www.prima.cse.salford.ac.uk:8080/~ibrarhussain/edit.jpg So i would click on an edit link and it would pre populate the text boxes. I don't have a problem with doing this, but how can i show the correct amount of input textboxes based on how many authors exist for that specific record? Can someone offer some advice please? The input elements are like so: Quote <input type="text" name="author[]" id="author1"/> <input type="text" name="author[]" id="author2"/> <input type="text" name="author[]" id="author3"/> ... ... ... <input type="text" name="author[]" id="author10"/> Some records may have 1 author some may have 10, so how can i do this? Thanks again.. Hi, what I want to figure out is for instance a person has registered with their country e.g. England. Now if I echo the country in a select box giving the person an option to change their country and Showing the person which currently they have selected already. The select box shows two England`s to select from. Could some one tell me how can I have one of each country and echo their already selected country from the database. I don't know how to explain any better what I am after but just basically there are two Englands showing one which is already selected (echoing from the mysql database) and one is already in the select box. Any help is much appreciated thank you. hi guys ive just finished this task after hours of head scratching since svg is only really supported good in firefox and opera ive chosen firefox as my browser to view this url www.deansignori.com/phpsvgpie/index.php i do need more help with this task but a different problem (creating select box to call different stylesheet and to change from 2d - 3d i have the code set out so that i can explode any segment or change size of slices or change from 2d-3d but i have to do this manually in the code to render different piecharts im wanting to use 1 but change it using a select box and echo my variable into it basically im unsure of the syntax for this problem psuedo code for style maybe something like if select box value isset onchange stylecolour echo stylecolour if select box value isset onchange stylegrey echo stylegrey and for 3d-2d if select box value isset onchnage format3 echo format3 if select box value isset onchange format2 echo format2 this would be on my index page can anyone advise me please regards Dean Hi Guys
I have a table which in it's shortened form has the following columns:
id | postID | title | content | version
The column for postID has a number that can be shared by multiple rows - differentiated by version number.
I want to run a query to select all records that are like a given keyword (i.e. %LIKE%) but where results share the same postID I only want to return the highest version number for that record.
The difficulty is some records may have multiple version numbers that match the like statement and some may have only one. So this variance with the LIKE search is causing me some confusion.
I've tried this in a few ways using a sub-query but for the life of me I cannot work out how to do it.
Any help would be appreciated,
Drongo
ok here's my problem $Sql1 returns two values: 8 and 10 and these numbers get put into a <select>. So far so good. I assign a onchange to it. When i select 8 it makes the changes but when I select 10 nothing happends. I preciate some help. Code: [Select] <?php require("status.php"); require("id.php"); $Link = mysql_connect($Host, $User, $Password); mysql_select_db('sportsportal', $Link); $Sql1 = "select distinct week, (select max(week) from coupons where user='$User') max from coupons where user='$User'"; $Result1 = mysql_query($Sql1, $Link); print "<tr>"; print "<td align=left valign=top> </td>"; print "<td align=left valign=top>"; print "<select name=current_week onchange=window.location='coupon.php?curwk='+this.value>"; while($Row1 = mysql_fetch_array($Result1)){ //if($Row1[week] == $Row1[max]){ //print "<option value='$Row1[week]' selected>Vecka $Row1[week]</option>"; //} else { //print "<option value='$Row1[week]'>Vecka $Row1[week]</option>"; //} print "<option value='$Row1[week]'>Vecka $Row1[week]</option>"; } print "</select>"; print "<p></td>"; print "</tr>"; if(isset($_REQUEST['curwk'])){ $Curwk = $_REQUEST['curwk']; } else { $Curwk = 0; } $Sql = "select home, away, home_score, away_score, winner from coupons where user='$User' and week='$Curwk'"; $Result = mysql_query($Sql, $Link) or die(mysql_error()); while($Row = mysql_fetch_array($Result)){ if(@$Row[home] == @$Row[winner]){ print "<tr>"; print "<td align=left valign=top> </td>"; print "<td align=left valign=top><b>$Row[home]</b> - $Row[away] $Row[home_score]-$Row[away_score]</td>"; print "</tr>"; } else { print "<tr>"; print "<td align=left valign=top> </td>"; print "<td align=left valign=top>$Row[home] - <b>$Row[away]</b> $Row[home_score]-$Row[away_score]</td>"; print "</tr>"; } } mysql_close($Link); ?> I'm trying to run a readout of a db which runs fine as an individual script. When I embed it in PHP inside an html div container, it bails when it encounters the first ">" and simply outputs the PHP characters from there through the "?>". The rest of the html runs fine before and after. For example, this line echo "<select>"; would output "; and any other php script up to the ?> end, after which it renders html fine. If I run the script as a separate php file, it runs as expected. Any help would be appreciated. Thanks. hi. just started a website talkietaco.com and at the momment my code selects the first row and displays it. this is all well and good but when i add a new row to the table it gos to the bottom. I want to be able to select the last row and echo it out. Any ideas? would i need to add an id row or something? Heres the code and thank you in advance for any help people can offer. Code: [Select] <?php $con = mysql_connect("localhost","",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mainbase", $con); $result = mysql_query("SELECT * FROM matteroffact"); echo "<table border='0'> <tr> <th></th> </tr>"; $row = mysql_fetch_array($result) or die(mysql_error()); echo "<tr>"; echo "<td><strong>" . $row['question']. "</strong> ". $row['answer']; "</td>"; echo "<tr>"; echo "</table>"; ?> Code: [Select] id player_id nat nt_caps 13740 28664 97 24 13741 28664 68 0 13742 28664 79 0 16252 42904 15 40 16253 42904 68 0 16254 42904 241 0 That's how my table looks. I want to select the player_id's that have either nt_caps = "0" for every nat OR player_id's that have nt_caps != "0" only for nat = "68". The SQL query I try to use is: SELECT player_id FROM x WHERE nat = '68' AND (nat != '68' AND nt_caps = '0') But then I get player_id '42904' and '28664' because they both have 1 entry that matches the query but I don't want them because they have nt_caps for another nat than nat "68". I hope you understand what I try to achieve. Hi everyone! I need to know how to write two $what_services variables in so it looks for both "R" AND "B".. R and B are values within my db table, here's the code: Code: [Select] <?php $what_services = "R"; $query = "SELECT * FROM companies WHERE what_services = '$what_services' ORDER BY approved DESC, company_name ASC"; $result = mysql_query($query); ?> iv'e tried the following but have gotten undesired results: two what services like so; $what_services = "R"; $what_services = "B"; separating with comma's; $what_services = "R, B"; Using AND; $what_services = "R AND B"; None of which works, what is the correct way to write this? Thanks I'm trying to write a select to match a few certain words... $sql = "SELECT * FROM podcasts WHERE `type` = 'podcast' AND recap LIKE 'Men%' AND recap LIKE '%Hockey%' ORDER BY date DESC"; That's what I have so far...which isn't working... I need to match the string "Mens" OR "Men's" with the word "Hockey" BUT...I can't match "Women's" or "Womens" Any idea what I'm doing wrong? The above code only returns 6 results...when it should return nearly 100. Thanks! |