PHP - Getting A Loop To Simply Write "static" Code ??
I am trying to make a loop simply write "static" code...if that is the correct explanation.... But it seems PHP wants to "process" such things as 'IF' and other Conditions which is defeating the purpose.
The problem specifically is that I NEED for a dynamic write to happen based on a variable that will put the following lines that start with IF (! isset // Make sure the checkbox arrays exist if (! isset($_POST['cp_checkbox_one'])) $_POST['cp_checkbox_one'] = array(); if (! isset($_POST['cp_checkbox_two'])) $_POST['cp_checkbox_two'] = array(); if (! isset($_POST['cp_checkbox_three'])) $_POST['cp_checkbox_three'] = array(); // here in the lines below is one way I have tried to make the the LINES ABOVE get written Dynamically // THIS PART returns the values I need, the checkbox names ---- // // foreach($_POST as $meta_key => $meta_value) { // if(cp_str_starts_with($meta_key, 'cp_checkbox')) { echo $meta_key; } // } // So that code WILL RETURN THE VALUES I NEED : // cp_checkbox_one, cp_checkbox_two, cp_checkbox_three // BASED ON THIS I WROTE THE FOLLOWING CODE-- BUT IT DOES NOT WORK AS A REPLACEMENT FOR A LINE // SUCH AS--- if (! isset($_POST['cp_checkbox_one'])) $_POST['cp_checkbox_one'] = array(); // function checkboxloop() { foreach($_POST as $meta_key => $meta_value) { if(cp_str_starts_with($meta_key, 'cp_checkbox')) { if (! isset($_POST[$meta_key])) $_POST[$meta_key] = array(); } } } // HERE I ASK FOR THE FUNCTION BUT WHILE I GET NO ERRORS I GET NO RESULTS // WHICH IS A PROPER SAVE OF UNCHECKED CHECKBOXES ON SUBMIT checkboxloop; I would very much appreciate knowing how to make the code keep looping whatever $meta_key names turn up on this page and then use those names to write the complete lines as STATIC PHP so that the IF conditions don't get "processed" while this function is called. In effect, I want to duplicate the effect of having the code lines WRITTEN, so that they perform exactly as if I had written them as PHP hard-code, as many lines as there will be $meta_keys, but not SEE the code--- just have it valid PHP. This function does NOT make the same thing happen internally. As soon as I replace the function with the HARD CODE PHP then it works...but, I have reached the stage where these lines of code have to happen dynamically. I am baffled how to get this to happen! If I use Echo then I get errors about the "IF". Thank you very much for your help! Similar TutorialsHi, bit stuck on how to find and replace "<" and ">" with "<" and ">". I basically have a database record that outputs to screen and I need the code in the <code> tags to be rendered to the screen. I therefore need it to go through the whole array variable from the db and change the symbols just inside the code tags. Please be aware that the code tags might happen more than once here's an example below Code: [Select] <p>blah blah blah</p> <p>blah blah blah</p> <p>blah blah blah</p> <code> <h1>hello</h1> </code> <p>blah blah blah</p> <p>blah blah blah</p> <p>blah blah blah</p> <code> <h1>hello</h1> </code> the desired output would be: <p>blah blah blah</p> <p>blah blah blah</p> <p>blah blah blah</p> <code> <h1>hello</h1 </code> <p>blah blah blah</p> <p>blah blah blah</p> <p>blah blah blah</p> <code> <h1>hello</h1 </code> help on this would be great Cheers Rob Can someone please help me with an array problem i can not figure out. I need the array to be numbered from 1 to how ever many fields that are needed in the form and have a mysql field name and the title of the field also in the array. 1, "mysql_field_name", "Title of form field" 2, "", "" and so on then the form will be shown based on the array. I have the following draft code which I am working with. any suggestions on how i may do this array ? Code: [Select] <?php $options = array( '1'=> array('fieldtext'=>'option1', 'mysqlfield'=>'option1'), '2'=> array('fieldtext'=>'option2', 'mysqlfield'=>'option2'), '3'=> array('fieldtext'=>'option3', 'mysqlfield'=>'option3'), '4'=> array('fieldtext'=>'option4', 'mysqlfield'=>'option4'), ); // $options = array(1 => "option1", "option2", "option3", "option4"); // the line above works but i want to include the name of the mysql field as well. $userid = 1; ?> <div style="align: center; margin: 12px; font-family:Tahoma;"> <br><br><?php if ($_POST['Update'] != "Update") { // check if form submitted yet, if not get data from mysql. $res = db_query("SELECT * FROM `users` WHERE `userid` = '" . $userid . "'"); foreach($options as $key => $value) { $_POST[$key] = mysql_result($res, 0, $value); } $ok_to_update = "no"; } elseif ($_POST['Update'] == "Update") { // check if form submitted yet, if so get POST data. // error checking // foreach($options as $key => $value) { // $_POST[$i] = ""; // } $ok_to_update = "yes"; } if ($_POST['Update'] == "Update" && $ok_to_update == "yes") { // $res = db_query("INSERT INTO `users` () VALUES ()"); // add user details to database. ?><p><br><br><br>Thank you for updating</p><?php } else { ?><form name="form1" method="post" action=""> <?php foreach($options as $key => $value) { ?><p><?php echo($value); ?>: <input type="text" name="<?php echo($key); ?>" value="<?php echo($_POST[$key]);?>"></p> <?php } ?> <input name="Update" type="submit" value="Update"> </form> <?php } ?> </div> I am trying to do a query for members in my database but I need to go through different tables to get those members I want. Let me try too describe: I want the members who has same team_id as current member (from same table) I want only the members who are online (from another table where time stamps are, which has members id, but not team id) I simply cannot figure out how to only get members with same team id as the current member, from the table with time stamps. Anyone can point me in the right direction, or is the above just not making sense at all?
Hi, <?php $string = "Mavic Mini, un quadrirotor reprenant le design pliable de ses aînés, mais pesant cette fois moins de 250 g et disposant de la meilleure autonomie de la famille 30 minutes annoncées."; $tmp = new clsMarkov(); $tmp->makeList($string); $tmp->buildTree(); print $tmp->phraseWriter('le', 111); // phraseWriter(mot de base, nombre de mots dans le résultat) ?>
On the last line the script says that the text must start with "le" and the text must be 111 words long. Hi guys I am a newbie with PHP and I have been trying to solve this problem for 3 days.. Ive set up a booking form on my website to be sent directly to my email once the client clicked on the send button.. The problem I am having while checking these pages on wamp is that the booking form is ok but when I click on the send button the following message error appears "Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\fluffy_paws\booking_form2.php on line 27" When I check online I have this message "500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed." Are my codes wrong??? My webhosting is Blacknight.com , Im on Windows Vista, my internet is a dongle with O2 ireland Thanks for your help! Hey, So on my profile page I have a lot of info such as Name, Birthday, City, Country, Status etc... Its set up like this... Name: $loggedInfo[Name]<p/> Birthday: $loggedInfo[Birthday]<p/> City: $loggedInfo[City]<p/> Country: $loggedInfo[Country]<p/> Status: $loggedInfo[Status]<p/> The problem is is that if the user doesnt fill out this info then there is a blank space on their profile. How can I go about having it so if there is no data for say Country, on their profile there will be a link and it will say "Edit this!" and that link can just go to edit profile. Pretty much I dont want to do this for everything... if($loggedInfo[Name] != "") { echo"$loggedInfo[Name]"; }else{ echo"<a href='edit_profile.php'>edit this!</a>"; } Thanks, Sean Hello: I wanted to see if someone knows how to do a "str_replace" before it's in the link .. This is the code I currently have and it does work, but I want the "str_replace" to take place before it gets added to the link: Code: [Select] <?php $query = "SELECT product_id,myTitle FROM myProducts ORDER BY myTitle ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $product_id = stripslashes($row['product_id']); $myTitle = stripslashes($row['myTitle']); ?> <li><a href="http://www.mywebsite.com/Promotional.Products-Promotional.Items/Promotional-Products/<?php echo $product_id ?>-<?php echo str_replace(" ", "-", $myTitle) ?>-<?php echo $full_state ?>-Promotional-Products.html" title="<?php echo $myTitle?> <?php echo "$full_state"; ?>"><?php echo $myTitle?></a></li> <?php } ?> Is there anyway I can make it happen here" Code: [Select] $myTitle = stripslashes($row['myTitle']); Everything I have tried has not worked .. Ideas? Hi guys I'm struggling a bit, I need to replace a word that occurs multiple times in text with an array("up","down","forward","backwards") of words. $find = "left"; $replace = array("up","down","forward","backwards"); $text = "left left left left"; echo str_replace($find,$replace,$text); The Output is: array array array array Did try this with a foreach statement as well, but no luck. Is there a better way of doing this? Thanks cant work out this mysql syntax error "operation":"medupdate","medid":"","name":"ibo","medyear":"5","medmonth":"21","medday":"1","recuser":1,"SuccFail":"fail","SuccFailMessage":"error occured You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''WHERE med_id=' at line 2","ResultData":""} Code: [Select] $sql="update metodology set med_description='".$req['name']."', med_year='".$req['medyear']."', med_month='".$req['medmonth']."', med_day='".$req['medday']."', med_recorddate= now(), med_recorduserid= 1'"; $sql.= " WHERE med_id=".$req['medid']; I've searched but can't seem to find anything I can apply to this situation. Most of the resources are dedicated to dropdown menu's from the same table. I have two tables 'regions' and 'cities' and I am looking to create a menu that lists all the cities within a region then moves on to do the same for the rest of the regions in that state: State1 Region1 City1 City2 City3 Region2 City1 City2 City3 Region3 Etc My tables: States table: stateID, state Regions table: regionID, region, stateID Cities table: cityID, city, regionID I currently have two pages- select region, then select city... I'd like to consolidate to one step after choosing a state. I know I need a nested loop, (while?), and to count the results somehow to retrigger loop; also not sure how to handle two mySQL querries in the nested loop. I'm having trouble wrapping my mind around it. Thank you. hello how do i pass a foreach loop through "Passing by Reference" say i have a foreach loop in a function like this: Code: [Select] function findText(&$output){ $word = Text::find_all(); foreach ($word as $words){ $output = $words->text; } } then one the page i put Code: [Select] findText($output); echo $output; that will just give me the last word in the database. so how do i get it to echo out the array on the page ? thanks Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys Working on changing sessions to be stored in db. Using example I found on Internet. Works for the most part, however it's driving me nuts that my username is being stored as data|s:6:"bertha"; vs. just the username bertha. I've read where the session_set_save_handler is "serializing" the data by default. In any case, I want to get at the username entered to ensure I keep my users logged in, etc. I've tried to "unserialize" the entry but it always returns false! MANY THANKS!! The code is below: //************************************************************************************* //Variables used through out the script - CHANGE TO A GENERAL FILE AND INCLUDE IT... //**************************************************************** $server = "blah"; // Server Name $userid = "blah"; // Username $pass = "blah"; //Password $database = "blah"; // Database Name //**************************************************************** //**************************************************************** //Make server and database connections //**************************************************************** $con = mysql_connect("$server",$userid,$pass) or die ("Connection Error to Server"); $db = mysql_select_db("$database",$con) or die("Connection Error to Database"); //========================================================================================== class SessionManager { var $life_time; function SessionManager() { // Read the maxlifetime setting from PHP $this->life_time = get_cfg_var("session.gc_maxlifetime"); // Register this object as the session handler session_set_save_handler( array( &$this, "open" ), array( &$this, "close" ), array( &$this, "read" ), array( &$this, "write"), array( &$this, "destroy"), array( &$this, "gc" ) ); } function open( $save_path, $session_name ) { global $sess_save_path; $sess_save_path = $save_path; // Don't need to do anything. Just return TRUE. return true; } function close() { return true; } //READ DATA function read( $id ) { // Set empty result //$data = ''; // Fetch session data from the selected database $time = time(); $newid = mysql_real_escape_string($id); $sql = "SELECT `session_data` FROM `sessions` WHERE `session_id` = '$newid' AND `expires` > $time"; $rs = mysql_query($sql); $a = mysql_num_rows($rs); if($a > 0) { $row = mysql_fetch_assoc($rs); $data = $row['session_data']; } return $data; } //WRITE DATA function write( $id, $data ) { //unserialize($data); //echo $data; // Build query $time = time() + $this->life_time; $newid = mysql_real_escape_string($id); //base64_encode(serialize $newdata = mysql_real_escape_string($data); $sql = "REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES('$newid','$newdata', $time)"; $rs = mysql_query($sql); //var_dump($_SESSION); return TRUE; } function destroy( $id ) { // Build query $newid = mysql_real_escape_string($id); $sql = "DELETE FROM `sessions` WHERE `session_id` = '$newid'"; mysql_query($sql); return TRUE; } function gc() { // Garbage Collection // Build DELETE query. Delete all records who have passed the expiration time $sql = 'DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();'; mysql_query($sql); // Always return TRUE return true; } }?> The calling page contains: require_once("sessions.php"); $sess = new SessionManager(); session_start(); Hi. A quick one: How do I write this in PHP? if (this variable don't contain "@") echo "This is not a valid email address"; Regards Morris I am getting the following error when using composer: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Just started. I am pretty sure composer.json wasn't changed. journalctl doesn't show anything. Maybe Doctrine related, however, nothing seems to help.
Any ideas? [michael@devserver www]$ php -v PHP 7.3.4 (cli) (built: Apr 2 2019 13:48:50) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.3.4, Copyright (c) 1998-2018 Zend Technologies with DBG v9.1.9, (C) 2000,2018, by Dmitri Dmitrienko [michael@devserver www]$ composer -V Composer version 1.4.2 2017-05-17 08:17:52 [michael@devserver www]$ yum info composer Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirror.us.oneandone.net * epel: mirror.rnet.missouri.edu * extras: mirror.us.oneandone.net * remi-php73: mirror.bebout.net * remi-safe: mirror.bebout.net * updates: mirror.us.oneandone.net Installed Packages Name : composer Arch : noarch Version : 1.8.4 Release : 1.el7 Size : 1.8 M Repo : installed From repo : epel Summary : Dependency Manager for PHP URL : https://getcomposer.org/ License : MIT Description : Composer helps you declare, manage and install dependencies of PHP projects, : ensuring you have the right stack everywhere. : : Documentation: https://getcomposer.org/doc/ [michael@devserver www]$ composer update Loading composer repositories with package information Updating dependencies (including require-dev) [ErrorException] "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [--with-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]... [michael@devserver www]$
This topic has been moved to Linux. http://www.phpfreaks.com/forums/index.php?topic=318175.0 Hi Guys Ever had the feeling your being a spoon and can't see the wood for the trees? Well, that's how I feel today. All I am trying to to is implement a variable in a "foreach" loop that increments by one through each iteration of the loop. I know how to do it in a "for" loop but can't for the life of me get it to work here. Here is the code: foreach ($cart as $prodcode => $qty) { $item = get_product_details($prodcode); echo '<input type="hidden" name="item_name_'.[b]$needavariablehere[/b].'" value="'.$item['description'].$_SESSION['finish'][$prodcode].$_SESSION['handles'][$prodcode].'" />' . "\n"; } Where I have highlighted $needavariablehere is where I want a number to appear i.e. if there is one item available and the foreach loop iterates once I want the number 1 here. If there are two items and the foreach loop iterates twice I want the output to have number 1 in the first line and number 2 the second time around and so on. How many times the foreach loop iterates is based on the $cart array which contains items in a shopping cart. Thanks for any help you can give guys. I'm getting an invalid argument error for my While loop. I can't figure out why. Code: [Select] $sql="SELECT * FROM schools ORDER BY class DESC,sectional ASC,team ASC"; $results = mysql_query($sql); while ($team = mysql_fetch_assoc($results)) { echo $team['school'] . '<br>'; } Here is the error: Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/******/public_html/hoosierhoopsmagazine.com/resources/sectional_assignments.php on line 7 question of perfomance .. Code: [Select] //take the names from table1 apply($sql1); foreach($names as $name){ //grab other info about the current user from table2 apply($sql2); } is this fine ? |