PHP - Limit Foreach To 3 Results
How can I limit my foreach to displaying three results?
In addition, how can I make it say... if results == 1 do this if results == 2 do this and if results == 3 do this Code: [Select] foreach($otherfans as $other) { $displayName = ucwords($other['firstname'].' '.$other['lastname']); ?> <a href="../u/<?php echo $other['username']; ?>"><?php echo $displayName; ?></a> <?php } Similar Tutorialshello, is there a wat to limit the following to only the first 25 characters? $customername=$row1["customer"]; thanks How can I limit the amount of time my while loop to only show the first 4 rows of my SQL table?
I am using this code to loop my whole table:
while($row = $results->fetch(PDO::FETCH_ASSOC)) { echo ' <li>Mileage: '.number_format($row["Mileage"]).'</li> <li>Engine size: '.$row["EngineSize"].'cc</li> ';} ?>I only want to loop through the first 4 rows of my SQL table, I then want to duplicate the same code but start at the 5th row until the 8th row of the table, how can I do this? Thanks, Nick I have the code below: ---------------------------------------------------------------------- ------------------------------------ <div id="content"> <table width="998" border="0" cellspacing="4" id="stuff"> <?php do { ?> <tr> <td><?php echo $row_Recordset1['name']; ?></td> </tr> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?> </table> <div id="spryTable" spry:region="ds1"> <table align="center"> <tr> <th spry:sort="name"> </th> </tr> <tr spry:repeat="ds1" spry:setrow="ds1" spry:hover="hover" spry:select="selected"> <td height="40" align="center">{name}</td> // green line <td height="40" align="center">{name}</td> //orange line </tr> </table> </div> ---------------------------------------------------------------------- -------------------------------- At the moment the green line of code will display the entire record of names, and the orange line displays the entire record again in another column of the table. The problem is, I want half the names to be printed in one column and the other half of names to be displayed in the other column. Can someone show me how to set the php code to do this? I've been trying various things for a while now without success. Thank you. Hi all, I need your help as I have got a problem with display the 50 rows in the search results. I want to limit 50 rows in per page and if I have less than 50 rows like 21 rows in the page 2 then display the 21 rows. I have got a problem with the limit, because when I tried to use `LIMIT 0, 50`, it will display total 71 rows which I only want to display no more than 50 in per page. Here is what I have tried: $search_mailbox = $link->prepare("SELECT * FROM $folder WHERE from_email LIKE ? OR subject LIKE ? OR message LIKE ? ORDER BY received_date DESC LIMIT 0, 50"); $search_mailbox->execute([$searchemail, $searchsubject, $searchmessage]);
$search_mailbox = $link->prepare("SELECT * FROM $folder WHERE from_email LIKE ? OR subject LIKE ? OR message LIKE ? ORDER BY received_date DESC LIMIT $offset, $limit"); $search_mailbox->execute([$searchemail, $searchsubject, $searchmessage]);
Here is the full code:
<?php // Initialize the session session_start(); //Connect to the database require_once('config.php'); $searchemail = '%' . 'gmail.com' . '%'; $searchsubject = '%' . 'gmail.com' . '%'; $searchmessage = '%' . 'gmail.com' . '%'; $mailbox = $link->prepare("SHOW TABLES"); $mailbox->execute(); $folders = array(); $total = 0; $total_rows = 0; $i = 0; while ($folder = $mailbox->fetch(PDO::FETCH_NUM)) { $folder = $folder[0]; if (strpos($folder, 'users') !== false) { $folder = str_replace('users', '', $folder); } else { $folders[$i] = $folder; } $i++; } foreach($folders as $folder) { $search_mailbox = $link->prepare("SELECT * FROM $folder WHERE from_email LIKE ? OR subject LIKE ? OR message LIKE ? ORDER BY received_date DESC LIMIT 0, 50"); $search_mailbox->execute([$searchemail, $searchsubject, $searchmessage]); if ($search_mailbox->rowCount() > 0) { $total += $search_mailbox->rowCount(); } } $page = 1; $limit = 50; //$per_page = 50; //$pages = ceil($total / $per_page); $offset = ($page - 1) * $limit; foreach($folders as $folder) { $search_mailbox = $link->prepare("SELECT * FROM $folder WHERE from_email LIKE ? OR subject LIKE ? OR message LIKE ? ORDER BY received_date DESC LIMIT $offset, $limit); $search_mailbox->execute([$searchemail, $searchsubject, $searchmessage]); if ($search_mailbox->rowCount() > 0) { foreach($search_mailbox->fetchAll() as $k => $row) { $email_number = $row['id']; $search_from = $row['from_email']; $search_subject = $row['subject']; $total_rows++; echo $search_subject . '.........................' . $total_rows; echo "<br>"; } } } ?> I am unable to fetch the first 50 rows in the page 1 and I am also unable to fetch the 21 rows in the page 2. What I am trying to achieve is when I am in page 1, I want to display the first 50 rows, then in the page 2 if I have another 50 rows then display the 50 rows, but if I have less than 50 rows like 21 rows then display the 21 rows. Can you please show me an example how I can start with first 50 rows when I am in the page 1 then in page 2 display 21 rows to make in total 71 rows? Any advice would be much appreicated. Thanks in advance. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=354388.0 Need help to correct my cording! I want to limited search results by 5 items on one page.
Don't know how correctly to add limit: "limit $page1,5".
When I add it: $sql = "SELECT * FROM data GROUP BY city ORDER BY city limit $page1,5";
it doesn't limit searching result by pages.
Attached Files
search3.php 1.67KB
5 downloads I am using a foreach loop to get the results of an array. My problem is that I need the results combined into one string. How can I accomplish this? I would like to write all files from specific folder into .txt file. The output working just fine, but I'm getting only one file saved into my txt file. Any idea? Thanks! $fileList = glob('C:\users\John\Documents\*pdf'); foreach($fileList as $filename){ if(is_file($filename)){ echo $filename, '<br>'; $save_files = fopen("list.txt", "w"); fwrite($save_files,$filename); fclose($save_files); } }
Hello everyone !
I am currently developing a module for my site that will allow me to classify each solution to help a disability by type. Type : Visual disability Solution : Add screen readers For this, I have a database in which these types and solutions are found. In this database, the solutions of one type or another are not in a defined order. They can be put randomly, when a user adds one. I need to display, in a table, these Types first (as a title), then the solutions corresponding to this type. I manage to generate a display thanks to a foreach loop, but my solutions are all mixed up and therefore not clearly sorted.
Visual disability Audio-described cut-scenes Highlighted path to follow Sensitivity settings for all the controls Screen readers on menus Slow down the game speed But I would need it to look like this: Visual disability Audio-described cut-scenes Highlighted path to follow Screen readers on menus Slow down the game speed Physical disability Sensitivity settings for all the controls In my example above, only the solution "Sensitivity settings for all the controls" is part of the "Physical disability" type. The rest is part of the "Visual disability" type. Here is the code I currently use to retrieve my information from my database and display it. It's a Wordpress.
/*====== Accessibility Options ======*/ function cloux_accessibility_options() { if ( function_exists( 'rwmb_meta' ) ) { $output = ""; $accessibility_options = rwmb_meta( 'accessibility-options' ); $accessibility_options_status = rwmb_meta( 'accessibility-options-status' ); if( $accessibility_options_status == "1" ) { if( !empty( $accessibility_options ) ) { $output .= '<div class="accessibility-options widget-box">'; $output .= cloux_title( $title = esc_html__( 'Accessibility Options', 'cloux' ), $style = "style-4", $align = "left", $colored_title = '' ); $output .= '<ul>'; $output .= '<li class="title visual_disability">' . esc_html__( 'Visual disability', 'cloux' ) . '</li>'; $output .= '</ul>'; foreach ( $accessibility_options as $accessibility_options ) { if( !empty( $accessibility_options ) ) { $accessibility_name = isset( $accessibility_options['accessibility-options-name'] ) ? $accessibility_options['accessibility-options-name'] : ''; $accessibility_type = isset( $accessibility_options['accessibility-type-name'] ) ? $accessibility_options['accessibility-type-name'] : ''; $accessibility_type = get_term( $accessibility_type, 'accessibility' ); $accessibility_type_name = $accessibility_type->name; $availability = isset( $accessibility_options['availability'] ) ? $accessibility_options['availability'] : ''; if ( $accessibility_type_name == "Visual disability" ){ if( !empty( $accessibility_name ) or !empty( $availability )) { $output .= '<ul>'; $output .= '<li class="item accessibility_name">'; if( !empty( $accessibility_name ) ) { $accessibility_name = get_term( $accessibility_name, 'accessibility' ); if( ( !empty( $accessibility_name ) ) ) { $output .= '<a href="' . get_term_link( $accessibility_name ) . '">' . esc_attr( $accessibility_name->name ) . '</a>'; } } $output .= '</li>'; $output .= '<li class="item visual_disability status">'; if( $availability == "1" ) { $output .= '<i class="fas fa-check" aria-hidden="true"></i>'; } else { $output .= '<i class="fas fa-times" aria-hidden="true"></i>'; } $output .= '</li>'; } } if ( $accessibility_type_name == "Motor/Physical disability" ){ if( !empty( $accessibility_name ) or !empty( $availability )) { $output .= '<ul>'; $output .= '<li class="item accessibility_name">'; if( !empty( $accessibility_name ) ) { $accessibility_name = get_term( $accessibility_name, 'accessibility' ); if( ( !empty( $accessibility_name ) ) ) { $output .= '<a href="' . get_term_link( $accessibility_name ) . '">' . esc_attr( $accessibility_name->name ) . '</a>'; } } $output .= '</li>'; $output .= '<li class="item visual_disability status">'; if( $availability == "1" ) { $output .= '<i class="fas fa-check" aria-hidden="true"></i>'; } else { $output .= '<i class="fas fa-times" aria-hidden="true"></i>'; } $output .= '</li>'; } } $output .= '</ul>'; } } $output .= '</div>'; } } return $output; } } Thank you in advance for all the help you can give me! Edited January 13 by Sagaroth Hello, i have the code below and i need to have all results in a variable as a string, inside the loop they are displayed how i want but outside will echo the last result. Thank You. Code: [Select] foreach($_POST as $key=>$value){ if (is_numeric($value)) { $valoare = "$value,"; } } echo $valoare; I have a search form that has a drop down Code: [Select] <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> I'm trying to limit the results in a foreach loop within what was selected. Meaning, if someone selects 10, results within 10 miles will show The foreach is Code: [Select] foreach ($stores as $k=>$v) { $output = "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['MktName']."</b><br>(approx ".$v." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'>".$storeinfo[$k]['LocAddSt']."<br>"; $output .= $storeinfo[$k]['LocAddCity'].", ".$storeinfo[$k]['LocAddState']." ".$storeinfo[$k]['zipcode']."</p>"; print_r($output); } $v being the distance. So I need to show only the results of $v that are less than $r. How would I go about doing this? Right now, $v displays numbers like 5.04, 173.9 and so forth. Can anybody help me out? Thanks in advance. Unless buffer overflows or breaking out of code to perform a new command are problems that have been solved.... I am trying to figure out the proper PHP method for setting a boundary on a variable within a script. I have this variable $name which is fed a value from $_POST['name'] from a form field. Now this form field is limited in the HTML to accept only 20 characters, but someone could easily edit the form or outgoing post data. So I want to know how to limit the variable size in the script. In other languages it could be something like this: var name(20). So how do I do that in PHP? This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } This code works fine without the LIMIT 5, but it lists all the results. With the LIMIT Code: [Select] $query = 'SELECT * FROM wp_playerRank WHERE year="2011" LIMIT 5 ORDER BY rankClass ASC'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) { Here is the error I'm getting: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/jwrbloom/public_html/resources/players/rank2011_top5.php on line 26 Hello friends, if i've database table (mytable) has the following ids 1 2 3 4 5 6 and i want to get it with limit the first (1 to 3 ) only Code: [Select] $sql ="select * from mytable LIMIT 3"; this will show the first 3 (1,2,3) how then i write code that shows which is after 3 so it shows me 4 5 6 and if there any way i can say Code: [Select] $sql ="select * from mytable LIMIT (first half of ids)"; and (shows 1,2,3..ect till half) Code: [Select] $sql ="select * from mytable LIMIT (second half of ids)"; will (shows 4,5,6...ect till end) thank you im using the floowing code to pull all alerts from the database. as you can see i have 3 types of alertsd. Profile alerts, forum alerts and topic alerts. They are sorted and placed on the screen under their respective header. However i want to limit it so it only displays 4 of each type of alert. I cant use LIMIT in the query because that would limit all alerts meaning only 4 alerts in total would show up and i just need to limit each alert type. any ideas? $alert_query = $link->query("SELECT a.a_aid, a.a_alert_type, a.a_time_alerted, a.a_fid, a.a_poster, a_alert_read, a.a_tid, c.f_name as cat_name, f.f_fid, f.f_name, t.t_name, u.u_avatar, u.u_avatar_cropped FROM ".TBL_PREFIX."alerts as a LEFT JOIN ".TBL_PREFIX."forums as f ON (f.f_fid = a.a_fid) LEFT JOIN ".TBL_PREFIX."topics as t ON (t.t_tid = a.a_tid) LEFT JOIN ".TBL_PREFIX."forums as c ON (c.f_fid = f.p_id) LEFT JOIN ".TBL_PREFIX."users as u ON (u.u_username = a.a_poster) WHERE a.a_user_name = '$user_name' ORDER BY a_time_alerted ") or die(print_link_error()); $alert_info = $alert_query->fetchAll(); $pm_alert_list = ''; $num_pm_alerts = 0; $num_forum_alerts = 0; $num_topic_alerts = 0; foreach($alert_info as $key => $val) { $alert_info[$key]['a_alert_read'] == 0 ? $color = '#f5dfaf' : $color = '#f4f4f4'; // if alert is a profile message alert if($alert_info[$key]['a_alert_type'] == 1) { $pm_alert_list .= '<dd style="background:'.$color.';" class="alert" id="alert-'.$alert_info[$key]['a_aid'].'"><p class="alert_intro">'; $pm_alert_list .= '<input type="checkbox" class="pm_checkbox" id="pm_checkbox-'.$alert_info[$key]['a_aid'].'" />'.profile_link($alert_info[$key]['a_poster']).' posted on your wall</p>'; $pm_alert_list .= '<p class="alert_time"> on '.asf_date($alert_info[$key]['a_time_alerted'],'full').'</p>'; $pm_alert_list .= '</dd>'; $num_pm_alerts++; } if($alert_info[$key]['a_alert_type'] == 2) { $forum_alert_list .= '<dd style="background:'.$color.';" class="alert" id="alert-'.$alert_info[$key]['a_aid'].'"><p class="alert_intro">'; $forum_alert_list .= '<input type="checkbox" class="pm_checkbox" id="pm_checkbox-'.$alert_info[$key]['a_aid'].'" /><strong><a href="'.$config['asf_root'].'category/'.create_url($alert_info[$key]['cat_name']).'/forum/'.create_url($alert_info[$key]['f_name']).'">'.$alert_info[$key]['f_name'].'</a></strong> has a new topic</p>'; $forum_alert_list .= '<p class="alert_time"> '.asf_date($alert_info[$key]['a_time_alerted'],'full').'</p>'; $forum_alert_list .= '</dd>'; $num_forum_alerts++; } if($alert_info[$key]['a_alert_type'] == 3) { $topic_alert_list .= '<dd style="background:'.$color.';" class="alert" id="alert-'.$alert_info[$key]['a_aid'].'"><p class="alert_intro">'; $topic_alert_list .= '<input type="checkbox" class="pm_checkbox" id="pm_checkbox-'.$alert_info[$key]['a_aid'].'" /><strong><a href="'.$config['asf_root'].'category/'.create_url($alert_info[$key]['cat_name']).'/forum/'.create_url($alert_info[$key]['f_name']).'/topic/'.create_url($alert_info[$key]['t_name']).'">'.$alert_info[$key]['t_name'].'</a></strong> has a new post</p>'; $topic_alert_list .= '<p class="alert_time"> '.asf_date($alert_info[$key]['a_time_alerted'],'full').'</p>'; $topic_alert_list .= '</dd>'; $num_topic_alerts++; } } Hi guys I have a problem. I limit the displayed rows by 10 (which works) and then a link saying "next" or "previous" The link itself works, but the site always just displays teh first 10 data entries. What do I do wrong? Thank you! Code: [Select] <?php $host="****"; // Host name $username="****"; // Mysql username $password="****"; // Mysql password $db_name="****"; // Database name $tbl_name="sp_users"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); //$sql="SELECT * FROM $tbl_name ORDER BY user_id"; $sql="SELECT * from sp_users,sp_schools where sp_users.user_id=sp_schools.school_id ORDER BY school_name LIMIT 0, 10"; $result=mysql_query($sql); $num_rows=mysql_num_rows($result); ?> <?PHP //check if the starting row variable was passed in the URL or not if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) { //we give the value of the starting row to 0 because nothing was found in URL $startrow = 0; //otherwise we take the value from the URL } else { $startrow = (int)$_GET['startrow']; } ?> <?PHP //this part goes after the checking of the $_GET var $fetch = mysql_query("SELECT * FROM sp_users,sp_schools where sp_users.user_id=sp_schools.school_id LIMIT $startrow, 10")or die(mysql_error()); ?> <style type="text/css"> <!-- .style2 {font-weight: bold} .style3 { font-family: Arial, Helvetica, sans-serif; color: #000000; } .style10 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; color: #000000; } #Layer1 { position:absolute; left:803px; top:36px; width:65px; height:28px; z-index:1; } #Layer2 { position:absolute; left:707px; top:19px; width:143px; height:39px; z-index:1; } #Layer3 { position:absolute; left:247px; top:463px; width:175px; height:53px; z-index:2; } --> </style> <title>User overview</title> </html> <div id="Layer2"> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"> <input type="hidden" name="foo" value="<?= $foo ?>" /> <input type="submit" name="submit" value="Refresh" /> </form></div> <div id="Layer3"><?PHP //now this is the link.. echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.($startrow+10).'">Next</a>'; ?> <?PHP $prev = $startrow - 10; //only print a "Previous" link if a "Next" was clicked if ($prev >= 0) echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.$prev.'">Previous</a>'; ?></div> <table width="779" border="0" align="left" cellpadding="0" cellspacing="1" bgcolor="#996600"> <tr> <td width="777"> <div align="left"> <table width="779" border="1" cellspacing="0" cellpadding="3"> <tr> <td colspan="6" align="center"><div align="center" class="style1 style3"><strong>SchoolPorta.com Users / Total: <?php echo $num_rows ?></strong></div></td> </tr> <tr> <td width="342" align="center"><span class="style2">school</span></td> <td width="62" align="center"><span class="style2">Name</span></td> <td width="104" align="center"><span class="style2">Lastname</span></td> <td width="130" align="center"><span class="style2">Email</span></td> <td width="64" align="center"><span class="style2">Update</span></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td><span class="style10"><? echo $rows['school_name']; ?></span></td> <td><span class="style10"><? echo $rows['user_first_name']; ?></span></td> <td><span class="style10"><? echo $rows['user_surname']; ?></span></td> <td><span class="style10"><a href="mailto:<?php echo $rows['user_login']; ?>"><?php echo $rows['user_login']; ?></a></span></td> <td align="center"><a href="update.php?id=<? echo $rows['user_id']; ?>" class="style10">update</a></td> </tr> <?php } ?> </table> </div></td> </tr> </table> <div align="left"> <p> </p> <p> </p> <p> </p> <p> <?php mysql_close(); ?> </p> </div> Im wondering if someone can shed some light on possibly the best way to do this. I currently have a website which recieves 26000-37000 visits a month. The host got on my case about to many MySql connections and with help from someone here decided a cache system was best. the cache system is now in place and only updates if the cached file is older than 5 days. I am still recieving high connections to my database and wonder if it is spam as i have a search box. the search box once filled in redirects to a page which queries the database for the keyword and displays results and because it was just selecting and not inserting into database i didnt go for the captcha. this is why i suspect spam, I have thought about limiting the amount of search queries per time limit by ip but I am unsure of how to tackle this and if it will help against spam bots? a google search has only found an answer which stores every visitors ip in a database and keeps count there which I cant see the benefit as it is creating more work for the DB. I have thought maybe creating a session variable that increments with every search and when searching checks this value but I am not to sure if this would help as it would be down to cookie settings. can anyone shed some light on a possible solution to this. I am not expecting you to write this for me but for now just to help with the best way to tackle the problem. Thank you for your time. |