PHP - How To Determine The Last Item In An Array That Is Being Looped Help!
I have this function, but it doesnt work. Basically the list outputs a list of news features, and puts a line under neath each article to seperate them. However once the last article has been reached, I don't want the break to be shown.
this is my code, any help would be appreciated as i am really struggling on this. Just need to determine the last item in the array, and stop the <hr split> from being output. function newsFeature(){ $event = "SELECT imgname, title, content, pkID from news ORDER BY date, time DESC LIMIT 5"; $event_page = query($event); $count = numRows($event_page); while ($row = mysql_fetch_assoc($event_page)) { $rowcount = $count; $para = substr($row['content'] , 0,100); $result .= '<article>'; $result .= '<a href="news-article.php?pkID=' . $row['pkID'] . '"><img src="uploads/thumbs/' . $row['imgname'] . '" alt="" width=116 height=83/ ></a>'; $result .= '<h2><a href="news-article.php?pkID=' . $row['pkID'] . '">' . $row['title'] . '</a></h2>'; $result .= '<p>' . $para . '...</p>'; $result .= '<p><a class="read-more" href="news-article.php?pkID=' . $row['pkID'] . '">Read more<span></span></a></p>'; $result .= '</article>'; if($row != end($row[])){ $result .= '<hr class="split">'; } } return $result; } Similar TutorialsHello, I'm going to be sending emails to users from a community calendar showing events for the day or a time frame specified elsewhere. The problem I'm having is turning results of DB query into a string when there are multiple results for the day. It works just fine with single results. I understand why it doesn't work but can't figure out how to solve the problem. Don't worry about the $eventdate as that comes from the same array as the $event_id used to call the array shown below. I tried foreach and implode but couldn't get it working so I'm starting over and asking for your guidance on how is the best way to pull this off. Thanks for your help. Code: [Select] $getevent = mysql_query("SELECT title, description from ".$conf['tbl']['events']." WHERE event_id=$event_id AND private=0"); WHILE ($gtevent = mysql_fetch_array($getevent)) { $event_title=$gtevent['title']; $event_description=$gtevent['description']; $message="<p><span style=\"font-size:24px\">$event_title</span><br />$eventdate</p><p>$event_description</p>"; } When will modern PHP copy an array by reference only instead of reassigning to memory? For instance, when I execute $bigArray=$stmt->execute([$id]), PHP utilizes memory to store the data. But then when I execute $dataHolders[] = new DataHolder($bigArray), I believe $bigArray is passed by reference and a new copy of $bigArray will not be stored in memory. If in DataHolder::__construct, I executed $data[]='bla', then it is my understanding that PHP would see that the array is being modified and will automatically make a copy, but I am not doing so and just state this to confirm my understanding. The part that I am uncertain about is not the first time data is retrieved but any additional times. When I execute the next $bigArray=$stmt->execute([$id]), will PHP need to first store in memory the array that DataHolder::data references, then release the memory associated with $bigArray, and then store in memory the new $bigArray?
<?php class DataHolder { private $data; public function __construct(array $data) { $this->data=$data; //$this->data[]='bla'; <-- I believe this will force PHP to make a new copy of the array but I am not doing so } } $dataHolders=[]; foreach($ids as $id) { $bigArray=$stmt->execute([$id]); $dataHolders[] = new DataHolder($bigArray); }
Say i have an array (called $myarray) and it has 10 numbers in it like this... 1 2 4 8 9 10 12 14 15 18 Now in my code, I get a number and lets say for this example it is "5". I need to see if that number is in the array --easy enough using in_array()--, but if it is NOT in the array, I need to find the next available number in the array that is greater than my starting number of 5 (which would be "8" in this example). But what is the best way to find this number (i.e. 8 in this example)? I imagine I need to somehow loop through but i'm not sure which loop is the best to use and i'm generally confusing the hell out of myself (which is frustrating because this is probably rather simple to do ). Can anyone help guide me in the right direction? Hello, Currently have an array like looks like the following when using print_r($session->items): Array ( [F1225] => 1 [EDS11147317] => 1 [1156D6RE001] => 1 [I111ADE47946] => 1 [S679AQ339] => 1 [S67914599] => 1 [CH111337631254] => 1 [S6787903647] => 1 [A11144O189] => 1 [F11144520] => 1 [121584Q12] => 1 [I11144661ADE] => 1 [S678829NB] => 1 ) I am trying to check if an item is in the array and if so, display a different result but currently every item says it is in the array when they are not (unless my logic is off...from the items I am looking at some should be included and some should not..but the below code is showing every item as having the same result). Example: foreach ($items as $item) { if (in_array($item->ItemID, $session->items)) { //$session->items is the array output above echo "In Array"; } else { echo "NOT in Array"; } } Currently everything say "In Array" when some should not. Am I using the in_array incorrectly? Thanks Everyone. Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } I have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! I'm trying to figure out how to add up all the $qty_total that exist into an overall total. I hope I'm not oversimplifying my example.. I have this: $qty_total = $qty_insert * $d['workshop_price']; $qty_insert loops several times and I want: $overall_total = $qty_total + qty_total + ...however many.. Hi, I want to loop out data from DB in <input> and change and update several posts at the same time. Can you give me a short example, how <input> and maybe foreach could look like? Thanks I cannot get this INSERT to work. Not records are being added to the sys_city_dev table. No query errors are being thrown. I am simply trying to add ALL records from all_illinois to sys_city_dev and Mid should have be add as 11 in all inserts. city_name of course will be field city_name from all_illinois. Here is my code: $query = "SELECT * FROM all_illinois"; if ($results = mysqli_query($cxn, $query)) { $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($rows = mysqli_fetch_array($results)) { echo $rows['city_name'] . "<br />"; $mid_id = '11'; $insert_city_query = "INSERT INTO sys_city_dev (ID, Mid, cityName, forder, disdplay, cid) VALUES (' ','" . $mid_id . "','" . $rows['city_name'] . "', '', '','')"; if (!$insert_city_query) exit(mysql_error()); } } } Here is my insert table structure and 5 records dump: -- -- Table structure for table `sys_city_dev` -- CREATE TABLE IF NOT EXISTS `sys_city_dev` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Mid` int(11) NOT NULL DEFAULT '0', `cityName` varchar(30) NOT NULL DEFAULT '', `forder` int(4) NOT NULL DEFAULT '0', `disdplay` int(4) NOT NULL DEFAULT '0', `cid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=113970 ; -- -- Dumping data for table `sys_city_dev` -- INSERT INTO `sys_city_dev` (`ID`, `Mid`, `cityName`, `forder`, `disdplay`, `cid`) VALUES (84010, 1, 'Dothan', 0, 0, 0), (84011, 1, 'Alabaster', 0, 0, 0), (84012, 1, 'Birmingham', 0, 0, 0), (84013, 2, 'Flagstaff', 0, 0, 0), (84014, 1, 'Auburn', 0, 0, 0); And the all_illinois dump w/ 5 records: -- -- Table structure for table `all_illinois` -- CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `all_illinois` -- INSERT INTO `all_illinois` (`state_id`, `city_name`) VALUES ('135', 'Abingdon'), ('135', 'Adair'), ('135', 'Addieville'), ('135', 'Addison'), ('135', 'Adrian'); Hi all, Im really struggling to build an update multiple records form, Ive built my table which calls all data i need from the db in a looped region which works fine I just cant understand how to then input these back into the table in the correct rows, if this makes sense? Ive been reading this tutorial but Its not very informative its more of a copy and paste http://www.phpeasystep.com/mysql/10.html Code: [Select] $new_array2=array_diff($my_array,$itemIds); $updatedb = mysql_query("UPDATE content_type_ads SET field_expire_value = '666' WHERE $new_array2 = field_item_id_value"); "$new_array2" has only 12 digit numbers for each item in the array, and I want to match them to the "field_item_id_value" field in the table, updating the "field_expire_value" field for the record where they match. I know I am close because the UPDATE code works before I add the WHERE statement (it of course adds '666' to EVERY field, but for a noobie it's a start!). Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. All, I have a zip code and for example the zip code is 01101. How can I determine if the first character in this is a zero? Thanks in advance. This may sound funny, but I'm not sure what I was trying to get this code to do... Code: [Select] <!-- Find Current Page Name --> <?php $page = basename($_SERVER['REQUEST_URI']); echo '<p>$page = ' . $page . '</p>'; // if ($page == '') { if (($page == '/')||($page == '')||($page == 'index.php')){ $page = "index.php"; echo '<p>You are on the Home Page.</p>'; }else{ echo '<p>You are on Some Other Page.</p>'; } What I mean by that is I'm not understanding why I chose... Code: [Select] if ($page == '') { and then... Code: [Select] if (($page == '/')||($page == '')){ and then... Code: [Select] if (($page == '/')||($page == '')||($page == 'index.php')){ Why would I get those different results from basename($_SERVER['REQUEST_URI'])?? And what should I expect locally on my Laptop with a Virtual Host set up (e.g. "http://local.debbie/index.php") versus using a Test Site (e.g. "http://www.doubledee.byethost2.com/") versus a real site (e.g. "www.debbie.com")?! Hope I'm making some sense here... Debbie I have a table that I must be populated based on a check box selection. The maximum selection is 5, however, there are more then 10 choices. For example: Here is a choice of 10 different (checkbox) options that the user can select from: 1. Coke 2. Root Beer 3. Pepsi 4. Dr. Pepper 5. Sprite 6. 7up 7. Cream Soda 8. Club Soda 9. Water 10. Milk I've already managed to limit the users selection to only 5. My issue is determining which of the checkboxese were actually selected so that I can correctly place them in my database. The first thing to do is create variables from all the checkboxes: $coke = $_POST['coke']; $rootbeer = $_POST['rootbeer']; $pepsi = $_POST['pepsi']; $drpepper = $_POST['drpepper']; etc. etc. Now that I have all 10 selections as variables from a submitted form how can I determine which ones are empty (or which ones have values) so that I can then save them to the database respectively? Am currently using this code, and actually thinking about it should split the query to an include in order to allow for other database drivers, on the chance we may decide to ditch the old MySQL. But I digress from the question. Code: [Select] include($lib."dbconfig.php"); $q = 'SELECT * FROM file WHERE this = "'.$that'"; $result = mysql_query($q); if (mysql_num_rows($result) > 0) If the query doesn't pick up a row I'm getting this error yo, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\webpages\*\*\admin.php on line 553 So what would be a better way of testing if the query was successful? I am pulling records from a mysql db. Example Output: Team A= Our Team Team b = An opponent team Team A score = 7 Team B score = 8 Team A = Our Team Team b = Another Opponent Team A score = 3 Team B score = 1 What I need now is to add ONE more output, which is whether this is a "WIN" or a "LOSS". Should I add a field into the table that calc's this? If so, how? Please be specific. Or, should I use php to compare Team A score vs Team B score PER every record and then insert this new variable into the output. If so, how do I create a new variable value for every single output in the table? I know ultimately that this is a IF THEN type of calc, but can't quite figure out how specifically. Please be specific. Thanks I have a Unique Constraint setup on (emailAddress and pin) to allow multiple email addresses be the same and multiple pins but not the same emailAddress and pin value together (unique(emailAddress, pin)) Anyway, I am trying to generate a pin through a random seed, but I can't get my code to work properly to test if the combination already exists. Here is the chunk that does not work: Code: [Select] $tries = 0; $foundRows=0; do { $pin=null; $tries++; $pin = str_pad(rand(0,9), 4, "0", STR_PAD_LEFT); $stmt = $dbh->prepare("SELECT COUNT(*) FROM ajax WHERE emailAddress=:email AND pin=:pin LIMIT 1"); if ($stmt->bindParam(':email', $email, PDO::PARAM_STR) && $stmt->bindParam(':pin', $pin, PDO::PARAM_INT)) { $stmt->execute(); $foundRows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn(); echo "<br />$foundRows<br />"; } else { die ("<p>Could not bind to data verification</p>"); } } while ($foundRows > 0); This is always returning $foundRows=0 so always exiting the loop, and giving me a constraint error. Any ideas? Maybe a better way to do this? My uploader allows the following file formats: jpg gif png I tested that if someone was to name a file configure.php.jpg, my uploader allows it to upload I want to do a check to see if the user has 2 extensions, and if so it will not allow them to upload. I was thinking of just checking if the file name has two "." (dots) in the name. What function could I use to do this? Or .. is there a better way? |