PHP - Repetitive Use Of A Function - How To Perform With An Array In A Loop
Similar TutorialsI want to loop through a MySQL table, and perform a calculation based on the current row the loop is on and the previous loop. Say my table has 2 columns - Film_id and FilmRelease, how would I loop through and echo out a calculation of the current FilmRelease and the previous row's column value? Thanks guys I have got to this stage, but for some reason it's not printing out anything Code: [Select] <?php mysql_connect("localhost", "****", "*****") or die(mysql_error()); mysql_select_db("*****") or die(mysql_error()); $sql = mysql_query("SELECT FilmRelease FROM Films_Info") or die(mysql_error()); $last_value = null; while ($row = mysql_fetch_assoc($sql)) { if (!is_null($last_value)) { print date_diff($row['FilmRelease'], $last_value) . "<BR>"; } $last_value = $row['FilmRelease']; } Hi Guys Sorry for the lame title but I have absolutely no idea how to word this. I have the following code which pulls message from a database: $messages_query = mysql_query("SELECT * FROM messages WHERE id='$message_id' AND recipient='$username'"); $messages_row = mysql_fetch_assoc($messages_query); $sender = $messages_row['sender']; $date = $messages_row['date']; $time = $messages_row['time']; $subject = $messages_row['subject']; $message = $messages_row['message']; $recipient = $message_query['recipient']; echo $sender . "<br />"; echo $date . "<br />"; echo $time . "<br />"; echo $subject . "<br />"; echo $message . "<br />"; As you can see, it only pulls the data if id='$message_id' AND recipient='$username'. I wish to perform a die ("You are not authorised to view this message!"); if id='$message_id' or recipient='$username' is different. Example: The database reads id: 1 & username: user The data would be displayed if $message_id = 1 and $username = user. The die would be performed if $message_id = 5 and $username = user I hope that makes sense, iv had a problem trying to word it correctly let alone come up with a solution. Does anybody know what i could do? Thanks Hi all. Here is my scripts which allow user to check multiple rows of data and delete it , but it require select data and click for twice to delete the rows , what should be the error? Code: [Select] <form name="frmSearch" method="post" action="insert-add.php"> <table width="600" border="1"> <tr> <th width="50"> <div align="center">#</div></th> <th width="91"> <div align="center">ID </div></th> <th width="198"> <div align="center">First Name </div></th> <th width="198"> <div align="center">Last Name </div></th> <th width="250"> <div align="center">Mobile Company </div></th> <th width="100"> <div align="center">Cell </div></th> <th width="100"> <div align="center">Workphone </div></th> <th width="100"> <div align="center">Group </div></th> </tr> </form> <? echo "<form name='form1' method='post' action=''>"; while($objResult = mysql_fetch_array($objQuery)) { echo "<tr>"; echo "<td align='center'><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"$objResult[addedrec_ID]\"></td>"; echo "<td>$objResult[addedrec_ID] </td>"; echo "<td>$objResult[FirstName]</td>"; echo "<td>$objResult[LastName] </td>"; echo "<td>$objResult[MobileCompany] </td>"; echo "<td>$objResult[Cell] </td>"; echo "<td>$objResult[WorkPhone] </td>"; echo "<td>$objResult[Custgroup] </td>"; echo "</tr>"; } echo "<td colspan='7' align='center'><input name=\"delete\" type=\"submit\" id=\"delete\" value=\"Delete\">"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) // from button name="delete" { $checkbox = ($_POST['checkbox']); //from name="checkbox[]" $countCheck = count($_POST['checkbox']); for($d=0;$d<$countCheck;$d++) { $del_id = $checkbox[$d]; $sql = "DELETE from UserAddedRecord where addedrec_ID = $del_id"; $result2=mysql_query($sql) or trigger_error(mysql_error());;; } if($result2) { $fgmembersite->GetSelfScript(); } else { echo "Error: ".mysql_error(); } } echo "</form>"; Thanks for every reply. Hi Folks,
Firstly I am new, I have read several topics here and learned a lot, I would class myself as 'slightly better than basic', but my knowledge is mostly gained from reading code.
I am making a simple POST form for work, the data gets inserted into MySQL, nice and easy, I can make it work if I write out the statement completely, BUT I need to make a new form, it will have HUNDREDS of input fields, I really don't want to write the code, and I figured programmatically is a good way to go anyway as forms change and new forms may be required, so I set about building a function to completely handle my post data, bind it to a statement and insert it into a table, I have scrapped it a half dozen times already because something fundamentally doesn't work, but I am very close! The function can write the statement, but I need to bind the POST values before I can insert, something going wrong here and I would appreciate some help, I have a feeling it's a problem with an array, but anyway I will show you what I have, give you some comments as to my reasoning, and hopefully you can help me with the last bit
public function getColumnNames($table){ $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; try { $stmt = $this->dbh->prepare($sql); $stmt->bindValue(':table', $table, PDO::PARAM_STR); $stmt->execute(); $output = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $output[] = $row['COLUMN_NAME']; } $all = array($output); $a1 = array_slice($output, 1); // I don't want column 1, it contains the ID, its auto incremented. $a2 = array_slice($a1, 0, -3); // I don't want the last 3 columns as they have default values $selected = array($a2); // contains all the columns except those excluded by array_slice, columns now match all of the input fields on the form foreach ($selected as $row){ $fields = "`" . implode('`, `', $row) . "`"; // I'm making `fields` here, $bind = ":" . implode(', :', $row); // And making :values here } return array ( "raw" => $all, "fields" => $fields, "bind" => $bind ); } catch(PDOException $pe) { trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR); } } public function addRecord(){ $col = array(); $col = $this->getColumnNames("table"); $raw = array($col['raw']); $fields = array($col['fields']); $bind = array($col['bind']); $columnList = implode('`, `', $fields); $paramList = implode(', ', $bind); $sql = "INSERT INTO `{$this->dbtable}` ($columnList) VALUES ($paramList)"; return $sql; // this returns something like: INSERT INTO `table` (`field1`, `field2`, `field3`) VALUES (:field1, :field2, :field3)";perfect I thought, now I just need to bind the values from $_POST... then I get stuck. Edited by luke3, 08 January 2015 - 12:10 PM. I am having some problems getting a query correct. Basically I have two tables, one with listings and another with categories. In the listings table I have a column called shortdescription. I am trying to pull the shortdescription from the listings table with the query $shortdesc = array_shift(mysql_fetch_row(mysql_query("select shortdescription from links where category = '".$scat->id."' "))); The shortdecription display properly on the pages display the listings, however I am getting the following error on any pages that only display the parent categories Warning: array_shift() [function.array-shift]: The argument should be an array in /home/...path/file.php on line 1462 The listings id numbers begin at 75+ because the initial parent category id ends at 74. The query seems to be searching for listing ids below 75 and spitting out an error because it is not finding them. Any ideas on how to eliminate this error and/or stop the query from looking for non-existant data? I want to define a function instead of repeating query in all my php pages. I call a function by passing an $id value and from that function i have to get all the info related to that id, like name, description and uom.
I am trying to do this, but i dont know how to get these values seperately.
here is my function
function items($item_id) { $details = array(); $result = mysql_query("select item_id, name, uom, description from items where item_id=".$item_id."") or die (mysql_error()); while($row = mysql_fetch_array($result)) { $details[] = array((stripslashes($row['name'])), (stripslashes($row['uom'])), (stripslashes($row['description']))); } return $details; }and i call my function like this $info = items($id);Can somebody guide me in this Hey Before I start playing around with some code I want to know if it is possible to call a function inside a while loop that will call echo a some stuff then return to the loop it got called by? thanks Hi guy, Does any know how to add a variable value to the name of a function in a loop e.g. Code: [Select] $i=1; while($qryRowName = mysql_fetch_assoc($qryName)){ $i++; function test$i(){ ***** } Is this possible? Please any help will be very much aprreciated Thanks } ok. say i have a list with a foreach loop in it. like this: Code: [Select] echo' <ul>'; $link = Link::find_all(); foreach($link as $links){ $name = $links->name; echo' <li>'.$name.'</li>'; } echo' </ul>'; now. say that i want to put this part : Code: [Select] $link = Link::find_all(); foreach($link as $links){ $name = $links->name; into a function so i can reuse the code... like this: FUNCTION Code: [Select] function(find_li){ $link = Link::find_all(); foreach($link as $links){ $name = $links->name; } Code: [Select] echo' <ul>'; find_li(); echo' <li>'.$name.'</li>'; } echo' </ul>'; the problem is the foreach } its not inside the function so the function will not work. but it needs to be after the </li> so that i get all the results in the <li> so is there a way to put the function before the <li> and the } after the </li> I have following in a csv file: sku,quantity,price ---------------------- ML2225-1/4,10,38.77 ML2225-1/4,20,36 ML2225-1/4,30,33.23 ML2225-5/16,10,35.94 ML2225-5/16,20,33.37 ML2225-5/16,30,30.8 ML2225-3/8,10,34.37 ML2225-3/8,20,31.92 ML2225-3/8,30,29.46 ML2225-7/16,10,34.37 ML2225-7/16,20,31.92 ML2225-7/16,30,29.46 ML2225-1/2,10,34.37 ML2225-1/2,20,31.92 ML2225-1/2,30,29.46 ... I am able to read the file (fgetcsv). How do I build an array for each unique sku set, then do something, then continue to the next unique sku set? Thanks, Mike i have 2 arrays... first array of lastnames, second array of firstnames lastAry = array('smith', 'jones', 'reed', 'chan') firstAry = array('mary', 'chris', 'kim', joe', 'sara', 'tim', 'amy', 'fred') how do i loop through each lastnames and turn into a string with firstname so it looks like : smith | mary | chris jones | kim | joe reed | sara | tim chan | amy | fred Hi I am trying to tidy up a bit of php code to make the end display much better but I am a bit stuck, I have the following code which takes a mysql query and uses the result to create a google graph. <?php $str = ""; $str .= "<img src='http://chart.apis.google.com/chart?chs=600x300"; $str .= "&chd=t:"; $i=0; while($row_Recordset3 = mysql_fetch_assoc($Recordset3)){ $reading_array[$i] = $row_Recordset3['reading']; $date_array[$i] = date("j/n", strtotime($row_Recordset3['date'])); $i ++; } $count=0; $count = count($reading_array); if($count>1) { $rstring = implode(",", (array_reverse($reading_array))); $dstring = implode("|", (array_reverse($date_array))); }else{ echo $count; } $str = $str.$rstring; $str = $str."&cht=lc&chxl=0:|"; // We will close the src attribute with \' and to print escape character ' we shall precede it with \ $str = $str.$dstring; $str = $str."&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity Generation for the last 35 days'"; $str = $str." >"; //we shall echo the $str that will display the graph ?> <tr><td> <?php echo $str; ?> Currently the result is http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|28/10|29/10|30/10|31/10|1/11|2/11|3/11|4/11|5/11|6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days I need to make it display only every 7 dates so that they are readable but I still need the pipes in between to space out the dates correctly so they tie in with the correct point on the graph, like this where I manually removed some dates as a demo http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|||||1/11|||||6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days This is beyond my limited stills, can anyone help please? Thanks Gordon I am working with wordpress. I am using a plugin that gets options stored in an array in the database. This is how I get the options Code: [Select] $options = get_option('option_tree'); echo $options['exc_cat']; the exc_cat is a key that stores a set of values. Right now with the code above, it echoes Array. If I do this Code: [Select] echo $options['exc_cat'][0]; it returns 5. Which is what I would expect it to do. What I can't figure out is how to get it to store each value which should be a number into 1 variable. What I need to do is loop through each value that is stored in the exc_cat key, return the number seperated by a -1,. So the result should look like this -1, -5 1 and 5 should be the only two numbers stored in the array at this point. Can you help? Thanks How can I loop an array and process in groups 100 at a time? Hello, I'm trying to loop out the following value from the below array and cannot figure it out - orders.orderid Could anyone help me? stdClass Object ( [recsindb] => 4320 [recsonpage] => 10 [9] => stdClass Object ( [orders.orderid] => 83269442 ) [8] => stdClass Object ( [orders.orderid] => 83267681 ) )
echo "<pre>"; Hello everyone! I am new here and this is my first post. I have been a member at another forum which they tend to make fun of newbies instead of helping them learn. That is why I am here Below is my script that allows me to upload 6 images at once and this works nicely. However, I am trying to change the variable $newname to increment in each pass so that I can build some if statements for my sql query. I would like the variable to start from $newname1 and should end up with 6 of them with the last being $newname6. That way I can have 6 unique picture variables that I can either update or insert into my table. Any help here would be great! Code: [Select] $upload_image_limit = 6; // How many images you want to upload at once? define('MAX_SIZE', '100'); define('UPLOAD_DIRECTORY', '../memberYard'); // Define a list of extensions we want to allow. $allowable = array('.gif', '.jpg', '.jpeg', '.png'); $errors = array(); if (isset($_POST['Submit'])) { if (!empty($_FILES)) { foreach ($_FILES as $file) { // No need for a separate function to get a file's extension $extension = substr($file['name'], strpos($file['name'], ".")); $size = filesize($file['tmp_name']); // Check if the file's extension is in the permissable list if (!in_array(strtolower($extension), $allowable)) { $errors[] = "File {$file['name']} is of an unknown type."; continue; } // Check that the file size is OK if ($size > MAX_SIZE * 1024) { $errors[] = "File {$file['name']} is too big."; continue; } // Generate a random name for the file and move it $newname = substr(md5(microtime()), 0, 12) . $extension; $copied = move_uploaded_file($file['tmp_name'], UPLOAD_DIRECTORY . DIRECTORY_SEPARATOR . $newname); if ($copied === FALSE) { $errors[] = "File {$file['name']} could not be uploaded."; } } } } ?> <div id="mainWrapper"> <div id="main"> <div class="top_bg"></div> <div class="description_pane"> <h2>Upload More Photos</h2> <?php if (!empty($errors)) { echo "<ul>"; foreach ($errors as $error) { echo "<li>{$error}</li>"; } echo "</ul>"; } ############################### HTML FORM while($i++ < $upload_image_limit){ $form_img .= '<label>Image '.$i.': </label> <input type="file" name="image'.$i.'"><br /><br />'; } $htmo .= ' <form method="post" action="" enctype="multipart/form-data"> '.$form_img.' <br /> <input type="submit" value="Upload Images" name="Submit" style="margin-left: 50px;" /> </form> '; echo $htmo; ?> <br /> </div> </div><!--end main --> <div class="main_bottom"></div> </div><!--end mainWrapper --> <? include '../templates/footer.php'; ?> i have an array in the loop but it isn't building up with results. i want it to check if the array exists, if not then create the array. Then in next loop it pushes a new value into the array. Below isn't working?... Code: [Select] while($row=mysql_fetch_assoc($get)); { $key = $row['keyword']; $scope= $_SESSION['scope']; if (!is_array($scope)) { $scopenew = array($key); $_SESSION['scope'] = $scopenew; } else { $scopenew = array_push($scope, $key); $_SESSION['scope'] = $scopenew; } } Code: [Select] // Get the users armour names $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); // Get the users overall protection $i=0; while($i < count($user_prot)) { $query1="SELECT * FROM armour WHERE id='$user_prot[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_prot[$i]=$array1["protection"]; $i++; } // set the users protection $user_protection=$armour_prot[0] + $armour_prot[1] + $armour_prot[2] + $armour_prot[3] + $armour_prot[4]; Is there a way to get them as one so: Code: [Select] $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $armour_prot[$i]=$array1["protection"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); Will that work and if so how would you then get the 2 different values out of say "$user_prot[0]". Cheers guys, Ruddy How do i do if i've reached of array? i know i could do end of loop. but the array is present many times in my code. Code: [Select] while($row = mysql_fetch_assoc($getdetails)) { $people = $row['people']; $_SESSION['people'][] = $people; if(end($_SESSION['people'])) { //code } } Hello, I am new to PHP and have come to a grinding halt in my project. I am attempting to dynamically generate values for Wordpress shortcodes ( [example] ). I have successfully created the shortcodes and am having trouble setting their value. When I call the function that is supposed to return the value for the shortcode, it returns empty. I can however hard code a string and have it returned to the function, thereby manually creating a value for the shortcode. However, because the shortcodes are being generated and filled dynamically, I need this function to work without specific values. I know this may sound like a Wordpress specific question, but I have a feeling it's just my lack of understanding of PHP operations. So, here is the basic layout: The name of the shortcode is generated from within a foreach loop that retrieves the name of custom fields on the post ($keyName). Code: [Select] $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'myFields'); } The add_shortcode function has two parameters ('name_of_shortcode', 'function_name'): Code: [Select] add_shortcode((string)$keyName, 'myFields'); I need the myFields function to return the value of $fieldValue from within the foreach loop. That's where the problem lies. This doesn't work: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } This does work: Code: [Select] function myFields() { return 'Content to replace the shortcode'; } This code will replace [shortcode] with "Content to replace the shortcode" in the post. The ultimate goal is: when [$keyName] appears anywhere within the post, it will display the content returned by the myFields function ($fieldValue). However, it's not working. I can't seem to pass the value of $fieldValue to the myFields function and thereby return it to add_shortcode. Any help is appreciated and I am awaiting anxiously to answer any questions. Here's all the code together: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'yourFunction'); } |