PHP - Creating An Array From A Database
I have a array for example:
Code: [Select] $item = array( "Great <em>Bittern</em>"=>"Botaurus stellaris", "Little <em>Grebe</em>"=>"Tachybaptus ruficollis", "Black-necked Grebe"=>"Podiceps nigricollis"); which will output Code: [Select] Array ( [Great Bittern] => Botaurus stellaris [Little Grebe] => Tachybaptus ruficollis [Black-necked Grebe] => Podiceps nigricollis ) how can I input data from a database so it comes out as the array assuming I have $row[3] and $row[0] as the data? for example Code: [Select] while($row=mysql_fetch_array($result)){ //$item.=array($row[3],$row[0]); //array_push($item,array($row[3]=>$row[0])); //$item.=array($row[3]=>$row[0]); $item.="[".$row[3]."]=>".$row[0]; } which of course doesnt work?? Similar TutorialsI'm trying to create a website, that echo's out a bunch of groups, where each group contains a group of checkboxes, containing A value, and a label for the checkbox, the way it is created right now, is foreach that echo's out a bunch of php arrays, which was easier than the static way before - But still, it's static in some way, or not very user friendly at the moment.. My problem is that I really want to write it in a database when I have the option. Is there anyone that can give some tips how to do? At the moment, my foreach looks like this: Code: [Select] echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">'; /* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */ $totalID=0; // this is a counter we use to build our check box names foreach ($items as $list){ $totalID++; // add one to the checkbox name counter echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox // $cbox now holds the item name, and point value echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n"; } } echo "</form>"; And my array is something like this: Code: [Select] $items['computers']['title']='Computer Brand'; $items['computers']['items'][]=array('Apple iMac',1); $items['computers']['items'][]=array('Apple Macbook',.5); $items['phones']['title']='Phone Brand'; $items['phones']['items'][]=array('iPhone',1); $items['phones']['items'][]=array('HTC',1); As said, I can write this, but takes time. I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do. My current database looks like this: Thank you! I am retrieving values in form of array from a database table and out of the I have to build multidimensional array depending upon the parent->child relationship in the same array. The result is as => Array ( => Array ( [label] => Shirt [uri] => # ) [1] => Array ( [label] => Jeans [uri] => # ) [2] => Array ( [label] => Lowers [uri] => # ) [3] => Array ( [label] => T-Shirts [uri] => # ) [4] => Array ( [label] => cotton shirt [uri] => # ) [5] => Array ( [label] => Trousers [uri] => # ) ) each is related to some parent-id. Can any body me any idea.
My longest post of the year..... (thank you in advance for scrolling 😀) Array ( [newQuantity77777] => 3 [newPrice77777] => 5.00 [usedQuantity77777] => 1 [usedPrice77777] => 3.99 [total77777] => 18.99 [newQuantity88888] => // sometimes empty [newPrice88888] => [usedQuantity88888] => 4 [usedPrice88888] => 12.00 [total88888] => 48.00 [newQuantity44444] => 2 [newPrice44444] => 4.00 [usedQuantity44444] => 0 [usedPrice44444] => 3.99 [total44444] => 8.00 // these values I don't need [date] => July 25 2021 // these values below I don't need [address] => 123 Anystreet Avenue [address2] => [zipcode] => 90210 [city] => Beverly Hills [state] => CA [planet] => Mars ) I've been trying to use that array to create a special "sub-array" for only the SKU numbers and just their new and used quantities and prices. DESIRED RESULT: Array ( [77777] => Array ( [newQuantity] => 3 [newPrice] => 5.00 [usedQuantity] => 1 [usedPrice] => 3.99 ) [88888] => Array ( [newQuantity] => 0 [newPrice] => 0 [usedQuantity] => 4 [usedPrice] => 12.00 ) [44444] => Array ( [newQuantity] => 2 [newPrice] => 4.00 [usedQuantity] => 0 [usedPrice] => 3.99 ) ) Knowing that my SKU numbers are always exactly 5 digits, and no other $_POST keys will ever have 5 digits, I've been able to accomplish this with horribly convoluted and unsatisfactory code like this: $sku = array(); foreach($_POST as $var => $val) { $number = substr($var,-5); if (preg_match("/\d{5}/",$sku)) { $sku[$number] = // the array keys will be the SKU numbers // then I keep looping to look for the string "newQuantity" // capture that value... and create little mini arrays // for my big multidimensional array..... Is there a better way to go about this? Thank you. Hi there I've been working with some code to display a single record on page. This all works fine and I'm able to pull what I want from the database. My problems is trying to use that data and turning it into something else like a link. I have a field in the database called image url which contains rows of image urls. So here is the problem area of the code: Code: [Select] <?php //////Displaying Data///////////// $id=$_GET['id']; // Collecting data from query string if(!is_numeric($id)){ // Checking data it is a number or not echo "Data Error"; exit; } $fetch=mysql_query("select * from productfeeds where ProductID=$id "); $row=mysql_fetch_object($fetch); echo mysql_error(); echo "<table>"; echo " <tr><td><b>ProductID</b></td><td>$row->ProductID</td></tr> <tr><td><b>ProductName</b></td><td>$row->ProductName</td></tr> <tr><td><b>ProductPrice</b></td><td>$row->ProductPrice</td></tr> //problem area for me <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> echo "</table>"; I'm trying to edit this part of the code: <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> I've tried this: <tr><td><b>Image</b></td><td><a href='{$row['URL']}'> <img src='{$row['ImageURL']}'></a> and <tr><td><b>Image</b></td><td><a href='$row['URL']'> <img src='$row['ImageURL']'></a> //removed brackets but I'm just getting errors. Can you guys help please? Thank you very much. Here is the sample page: http://hoosierhoopsreport.com/pg-test/ Trying to create a table that has three sections (groupings). That part I have figured out. The first grouping is sorted numerically. The second group is sorted alphabetically based on what part of the state they live in. It's breaking down this second part that I can't seem to get. (The third group is just what's left over, sorted alphabetically.) So it needs to look like this: (Each group and region have their own header row. Only Group 2 is broken down into Regions.) Group 1 Group 2 -Region 1 -Region 2 -Region 3 -Region 4 -Region 5 Group 3 The sample page above, in Group 2, it just shows Region 1 header. Code: [Select] $query = 'SELECT * FROM a_playerRank WHERE year="2015" and position="1" ORDER BY grouping DESC,rankPos,region,nameLast'; $results = mysql_query($query) or trigger_error('MySQL error: ' . mysql_error()); $currentGrouping = false; $currentRegion = false; while($line = mysql_fetch_assoc($results)) { if($currentGrouping != $line['grouping']) { //Status has changed, display status header $currentGrouping = $line['grouping']; if($line['grouping']==2) { echo '<thead> <tr> <th class="num">#</th> <th class="top">Top 10</th> <th class="height">HT</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="level">Level</th>'; } echo' <th class="school">City (School)</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="summer">Summer Team</th>'; } echo' <th class="college">College</th> </tr> </thead>'; } if($line['grouping']==1) {echo '<tr><th colspan="7">Best of the Rest</th></tr>'; if($currentRegion != $line['region']) { $currentRegion = $line['region']; echo '<tr><th colspan="7">Region' .$line['region'] . '</th></tr>';} } if($line['grouping']==0) echo '<tr><th colspan="7">Names to Know</th></tr>'; } Hello, I've created a page search to return results from my database inventory. On top of these results I would like to display a seperate list of five products not included in the search results but share the same sub_category_b (a column in my SQL table). Posted below is my primary query of the database. If anyone can help me out with this it would be appreciated. Code: [Select] $colname_product = "-1"; if (isset($_GET['title'])) { $colname_product = $_GET['title']; } mysql_select_db($database_inventory, $inventory); $query_product = sprintf("SELECT * FROM inventory WHERE item_name LIKE %s OR item_desc LIKE %s ", GetSQLValueString("%" . $colname_product . "%", "text"),GetSQLValueString("%" . $colname_product . "%", "text")); $product = mysql_query($query_product, $inventory) or die(mysql_error()); $row_product = mysql_fetch_assoc($product); I've fooled around with this one for some time and haven't come up with a clear cut answer. Thank you in advance! Hello, I have found the following code which creates a sitemap from the home directory of files. Please could you point me in the right direction for changing this so that it looks up from my sql database and for each name within the database creates an entry in the sitemap (e.g. www.mysite.com/[NAME]). Thanks for your help, Stu Code: [Select] <?php /******************************************************************************\ * Author : Binny V Abraham * * Website: http://www.bin-co.com/ * * E-Mail : binnyva at gmail * * Get more PHP scripts from http://www.bin-co.com/php/ * ****************************************************************************** * Name : PHP Google Search Sitemap Generator * * Version : 1.00.A * * Date : Friday 17 November 2006 * * Page : http://www.bin-co.com/php/programs/sitemap_generator/ * * * * You can use this script to create the sitemap for your site automatically. * * The script will recursively visit all files on your site and create a * * sitemap XML file in the format needed by Google. * * * * Get more PHP scripts from http://www.bin-co.com/php/ * \******************************************************************************/ // Please edit these values before running your script. //////////////////////////////////// Options //////////////////////////////////// $url = "http://www.WEBSITE_NAME.com/"; //The Url of the site - the last '/' is needed $root_dir = ''; //Where the root of the site is with relation to this file. $file_mask = '*.php'; //Or *.html or whatever - Any pattern that can be used in the glob() php function can be used here. //The file to which the result is written to - must be writable. The file name is relative from root. $sitemap_file = 'sitemap.xml'; // Stuff to be ignored... //Ignore the file/folder if these words appear in the name $always_ignore = array( 'local_common.php','images' ); //These files will not be linked in the sitemap. $ignore_files = array( '404.php','error.php','configuration.php','include.inc' ); //The script will not enter these folders $ignore_folders = array( 'Waste','php_uploads','images','includes','lib','js','css','styles','system','stats','CVS','.svn' ); //The default priority for all pages - the priority of all pages will increase/decrease with respect to this. $starting_priority = ($_REQUEST['starting_priority']) ? $_REQUEST['starting_priority'] : 70; /////////////////////////// Stop editing now - Configurations are over //////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// function generateSiteMap() { global $url, $file_mask, $root_dir, $sitemap_file, $starting_priority; global $always_ignore, $ignore_files, $ignore_folders; global $total_file_count,$average, $lowest_priority_page, $lowest_priority; /////////////////////////////////////// Code //////////////////////////////////// chdir($root_dir); $all_pages = getFiles(''); $xml_string = '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd"> <?php # '; $modified_priority = array(); for ($i=30;$i>0;$i--) array_push($modified_priority,$i); $lowest_priority = 100; $lowest_priority_page = ""; //Process the files foreach ($all_pages as $link) { //Find the modified time. $handle = fopen($link,'r'); $info = fstat($handle); fclose($handle); $modified_at = date('Y-m-d\Th:i:s\Z',$info['mtime']); $modified_before = ceil((time() - $info['mtime']) / (60 * 60 * 24)); $priority = $starting_priority; //Starting priority //If the file was modified recently, increase the importance if($modified_before < 30) { $priority += $modified_priority[$modified_before]; } if(preg_match('/index\.\w{3,4}$/',$link)) { $link = preg_replace('/index\.\w{3,4}$/',"",$link); $priority += 20; } //These priority detectors should be different for different sites :TODO: if(strpos($link,'example')) $priority -= 30; //If the page is an example page elseif(strpos($link,'demo')) $priority -= 30; if(strpos($link,'tuorial')) $priority += 10; if(strpos($link,'script')) $priority += 5; if(strpos($link,'other') !== false) $priority -= 20; //Priority based on depth $depth = substr_count($link,'/'); if($depth < 2) $priority += 10; // Yes, I know this is flawed. if($depth > 2) $priority += $depth * 5; // But the results are better. if($priority > 100) $priority = 100; $loc = $url . $link; if(substr($loc,-1,1) == '/') $loc = substr($loc,0,-1);//Remove the last '/' char. $total_priority += $priority; if($lowest_priority > $priority) { $lowest_priority = $priority;//Find the file with the lowest priority. $lowest_priority_page = $loc; } $priority = $priority / 100; //The priority is given in decimals $xml_string .= " <url> <loc>$loc</loc> <lastmod>$modified_at</lastmod> <priority>$priority</priority> </url>\n"; } $xml_string .= "</urlset>"; if(!$hndl = fopen($sitemap_file,'w')) { //header("Content-type:text/plain"); print "Can't open sitemap file - '$sitemap_file'.\nDumping result to screen...\n<br /><br /><br />\n\n\n"; print '<textarea rows="25" cols="70" style="width:100%">'.$xml_string.'</textarea>'; } else { print '<p>Sitemap was written to <a href="' . $url.$sitemap_file .'">'. $url.$sitemap_file .'></a></p>'; fputs($hndl,$xml_string); fclose($hndl); } $total_file_count = count($all_pages); $average = round(($total_priority/$total_file_count),2); } ///////////////////////////////////////// Functions ///////////////////////////////// // File finding function. function getFiles($cd) { $links = array(); $directory = ($cd) ? $cd . '/' : '';//Add the slash only if we are in a valid folder $files = glob($directory . $GLOBALS['file_mask']); foreach($files as $link) { //Use this only if it is NOT on our ignore lists if(in_array($link,$GLOBALS['ignore_files'])) continue; if(in_array(basename($link),$GLOBALS['always_ignore'])) continue; array_push($links, $link); } //asort($links);//Sort 'em - to get the index at top. //Get All folders. $folders = glob($directory . '*',GLOB_ONLYDIR);//GLOB_ONLYDIR not avalilabe on windows. foreach($folders as $dir) { //Use this only if it is NOT on our ignore lists $name = basename($dir); if(in_array($name,$GLOBALS['always_ignore'])) continue; if(in_array($dir,$GLOBALS['ignore_folders'])) continue; $more_pages = getFiles($dir); // :RECURSION: if(count($more_pages)) $links = array_merge($links,$more_pages);//We need all thing in 1 single dimentional array. } return $links; } //////////////////////////////// Display ///////////////////////////// ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.1 Transitional//EN"> <html> <head> <title>Sitemap Generation Using PHP</title> <style type="text/css"> a {color:blue;text-decoration:none;} a:hover {color:red;} </style> </head> <body> <h1>PHP Google Search Sitemap Generator Script</h1> <?php if($_POST['action'] == 'Create Sitemap') { generateSiteMap(); ?> <h2>Sitemap Created...</h2> <h2>Statastics</h2> <p><strong><?php echo $total_file_count; ?></strong> files were found and indexed.<br /> Lowest priority of <strong><?php echo $lowest_priority; ?></strong> was given to <a href='<?php echo $lowest_priority_page; ?>'><?php echo $lowest_priority_page; ?></a></p> Average Priority : <strong><?php echo $average; ?></strong><br /> <h2>Redo</h2> <?php } else { ?> <p>You can use this script to create the sitemap for your site automatically. The script will recursively visit all files on your site and create a sitemap XML file in the format needed by Google. </p> <p>You can customize the result by changing the starting priorities.</p> <h2>Set Starting Priority</h2> <?php } ?> <form action="create_sitemap.php" method="post"> Starting Priority : <input type="text" name="starting_priority" size="3" value="<?php echo $starting_priority; ?>" /> <input type="submit" name="action" value="Create Sitemap" /> </form> </body> </html> Okay, I'll make this short and sweet, and all side comments are irrelevant. I'm doing this for my own happies So using Facebook.com's API you can extract all of a specific user's friends in an array. Well I'm making a array check to see who on that users friend list was removed or deleted them that week using array_dif(); in this method: 1) User allows the application 2) Application catches the user's friends_id's in an array and stores them // this is where i'm having trouble, i'll come back to it 3) User then waits a few days and notices their friend count is no longer 400, it's now 399! 4) User logs into my application, and checks the previously uploaded array against their current array of friends. Okay now to the part i'm struggling with is, what would you do? Should i store them each uniquely in a database? Because some users have 4,000+ friends and that gets quite strenuous. OR! Should i save them into a txt file unique to that person's user_id. I kind of like the 2nd option, however it's less ( to my newbish mind ) customizable versus the sql_queries. Once again, i'd like to reiterate, i don't care that this is again Facebooks terms of service, it's for my own personal gain and just enjoy taking on projects in my spare time that force my brain to work hard. That's all, hope you excuse the typos and poor grammar. Typed this pretty quickly, any questions - feel free to ask! All I am not the best at PHP and have been trying to work out how to make a treeview from an array. I managed to get as afar as populating my array as i would like and I can get those values back but now im really stuck What id love to be able to do is use my area field as the parent and my title field as the child and have a counter on the parent with no of child nodes. If someone can help me out with that bit id be really greatful, as I ve already sorted my javascript etc this is my last problem and its driving me nuts Many Thanks for looking and i really do appreciate any help Gibbo <?php $row = 0; $myarray = array(); foreach ($view->result as $result) { $arg = $view->render_field('field_decision_type_value', $row); $arg2 = $view->render_field('title', $row); $myarray[$row]["area"]=$arg; $myarray[$row]["title"]=$arg2; $row++; } asort($myarray); $last = count($myarray) - 1; $rowcount=0; while ($rowcount <= $last) { print $myarray[$rowcount]["area"]; print $myarray[$rowcount]["title"].'|<br />'; $rowcount++; } ?> Hello I was trying from days to create an array from a txt file by i can't make it happen. I am so desperate now and i want your help guys The code create a txt file from a textarea feild after it's submited each on a line. After that the php code need collect these data from the txt file and create an array from them. Example: if i type in the textarea: test test1 test2 I want these usernames to be inserted in the array so it would be like this: $names = array('test','test1','test2'); Anyone can help me This is the code <html> <head> <title></title> <style type="text/css"> body{ background-color:#1166aa; } #mainbox{ width:inherit; background-color:#FFFFFF; padding:14px; border:solid 3px #000000; float:left; } #mainbox2{ background-color:#CCCCCC; border:solid 2px #000000; padding:11px; } #contaner{ border:solid 0px #00FF00; } h1:hover{ color:#0000CC; cursor:pointer; } #msg{ cursor:pointer; } table td{ border-top:outset 1px #999999; } #amount{ color:#FF0000; cursor:crosshair; } #to{ color:#3300FF; } #from{ color:#3300FF; } #subject{ color:#3300FF; } </style> </head> <body alink="#003399" vlink="#003399"> <?php ///////////////////////////////////////////////// function create_list(){ $list= ($_GET ['name_list']); $file= "list.txt"; $file_pointer = fopen($file ,'w'); fwrite($file_pointer , $list); fclose($file_pointer); } ////////////////////////////////////////////////// $list= ""; create_list(); ////////////////////////////////////////////////// function explodeRows($data) { $rowsArr = explode("\n", $data); return $rowsArr; } $filename = "list.txt"; $handle = fopen($filename, 'r'); $data = fread($handle, filesize($filename)); $rowsArr = explodeRows($data); for($i=0;$i<count($rowsArr);$i++) { $name = explodeRows($rowsArr[$i]); function name(){ $names = array('the usernames submited to be inserted here','the usernames submited to be inserted here',.......); } } //////////////////////////////////////////////////// if ($_GET ['submit'] == "submit"){ create_list(); name(); } ?> <script type="text/javascript"> function foo(textarea,limit){ var val=textarea.value.replace(/\r/g,'').split('\n'); if(val.length>limit){ alert('You can not enter\nmore than '+limit+' lines'); textarea.value=val.slice(0,-1).join('\n') } } </script> <table align="center" id="contaner"> <tr><td> <form action="<?php $_SERVER [SERVER_NAME]; ?>" method="get"> <div id="mainbox"> <div id="mainbox2"> <table> <tr> <td>name List :</td> </tr> </table> <textarea id="name_list" name="name_list" cols="60" rows="9" onkeyup="foo(this,50)"></textarea> </div> <tr> <td><center><input name="submit" type="submit" value="submit"/></center></td> </tr> </div> </form> </tr></td> </table> </body> </html> Alright, this has been puzzling me for a while now and I think it's time I seek help before my brain turns to mush. I've been modifying a PHP text based game called Legend of the Green Dragon to add more functionality, etc. One of the things I want to add is the ability to add levels higher then 15. The original array looks like this: $exparray = array(1=>100,2=>400,3=>1002,4=>1912,5=>3140,6=>4707, 7=>6641,8=>8985, 9=>11795,10=>15143,11=>19121,12=>23840, 13=>29437,14=>36071,15=>43930, ); Now, I could just hardcode each level, but noo, I want to be able to do it from a module type thing from the admin panel (which I've already gotten that working gratefully) so I've tried writing a few different scripts to take the information from the MySQL database and turn it into an array like above but I've gotten completely lost. This is what I currently have: $expsql = "SELECT * FROM " . db_prefix("myolevels"); $numrows = mysql_num_rows($expsql); for ($i = 1; $i <= $numrows; $i++) { $expresult = mysql_query($expsql); while ($rows = mysql_fetch_assoc($expresult)) { $exparray = array($i=>$rows['myoexpreq']); } } Although when I call the array, it always returns null for the myoexpreq causing your master to look for you all the time (forcing level up when it shouldn't be). Is there any way to create an array like the first with SQL? Thought this might help as well: PHP Warning: "Variable passed to each() is not an array or object" in /home/ileetcom/public_html/logd/lib/experience.php at 35. Call Stack: 2: each(NULL) called from /home/ileetcom/public_html/logd/lib/experience.php on line 35 3: exp_for_next_level(16, "0") called from /home/ileetcom/public_html/logd/village.php on line 131 Hi. I need some help working something out. I have an array that has all the numbers from, 0 to 9. What I want to do is loop through the array to make all the combinations possible up to a string thats 255 chars long. $array = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ); Should be looped through to create strings like this: Code: [Select] 0 1 2 3 4 5 6 7 8 9 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 etc.. Just as if it's counting. Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> I have a simple detection for mobile devices and it works fine but it has gotten a bit bloated so I tried to put the list in an array. I don't get errors but it doesn't work. Here is what I tried $useragents = array("iPhone","iPod","incognito","webmate","Android","dream","CUPCAKE","blackberry9500","blackberry9530","blackberry9520","blackberry9550","blackberry 9800","webOS","s8000","bada","Googlebot-Mobile"); if (in_array(1, $useragents)) { $phones = strpos($_SERVER['HTTP_USER_AGENT'], $useragents); } if ($phones == true) { include_once './template/phones.php';} Please assist I need to extract shopping cart transaction information from a database, convert it to json format and send to another DB. Because the fields are not a direct match the calculated values are first bing put into variables. I'm extracting the line items from the database into an array and looping through the array to get each line item which I want to then insert into another array as a sub array. By the way, I'm new at PHP so be gentle. The first step I've coded as: Code: [Select] foreach ($oit_array as $inner1) { // Check type if (!is_array($inner1)) {$inner1 = array($inner1);} $lineprice+=$inner1[orderitem_price]; //calculate amounts required in variables $linepriceinc=$inner1[orderitem_price]+($inner1[orderitem_tax]/$inner1[orderitem_quantity]); if($inner1[orderitem_tax]==0){$linetaxrate+=0;} else $linetaxrate=($inner1[orderitem_final_price]-$inner1[orderitem_tax])/$inner1[orderitem_tax]; $linetaxtotal+=$inner1[orderitem_tax]; $orderqty+=$inner1[orderitem_quantity]; $productname=$inner1[orderitem_name]; $qtyshipped+=$inner1[orderitem_quantity]; $totallineamount+=$inner1[orderitem_final_price]-$inner1[orderitem_tax]; $totallineamountinc+=$inner1[orderitem_final_price]; $unitofmeasure="Units"; $linearray[] = array("LinePrice"=>$lineprice, "LinePriceInc"=>$linepriceinc, "LineTaxCode"=>"GST", "LineTaxRate"=> $linetaxrate, "LineTaxTotal"=> $linetaxtotal, "OrderQty"=> $orderqty, "ProductName"=> $productname, "QtyShipped"=> $orderqty, "TotalLineAmount"=> $totallineamount, "TotalLineAmountInc"=>$totallineamountinc, "UnitOfMeasure"=>"Units"); I then reference the array as $linearray as follows: Code: [Select] //Create Array $salesarray= array ("type"=> "TCashSale", "fields"=>array ("CustomerName"=>$customername, "ShipToDesc"=>$shiptodesc, "Lines"=> array("type"=> "TCashSaleLine", "fields"=> $linearray)), "SalesPayments"=>array("type"=>"TSalesPayments", "fields"=>array("Amount"=> $amount, "PayMethod"=> $paymentmethod))); The problem that I have is that the resulting array contains square brackets around the "linearray" data like so: Code: [Select] {"type":"TCashSale","fields":{"CustomerName":"Cash Customer","ShipToDesc":"Rod Farrell\n\r1234 Short St\n\r\n\rSlackville Queensland 4001","Lines":{"type":"TCashSaleLine","fields":[{"LinePrice":54.54545,"LinePriceInc":54.54545, What am I doing wrong?? I have four different arrays and I want to place them into a multi dimensional array and then I want to place it into a Session variable. This is what I have below.How do I do this? when I print_r($_Session) I don't get anything just option[](2); Code: [Select] $_SESSION ['option']['green'] = array('name '=>'jeff'); $_SESSION ['option']['red'] = array('name '=>'mary'); $_SESSION ['option']['blue'] = array('name '=>'joe'); $_SESSION ['option']['brown'] = array('name '=>'ash'); Hi guys, Is there an html code that allows you to array a form input? and once you passed the form, how do you extract the data then insert it to the database? Thanks Hi, I want to develop array like following Code: [Select] $BCD=array('type' =>'TYPE1', array( 0=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 1=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 2=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 3=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), ) )); I have written following code to achieve the same but not getting result. Code: [Select] $sql = "select * from tablename "; $result = mysql_query($sql); $k=0; while ($row = $db->mysql_fetch_array($result)) { // array_push($BCD['type'],$row['type']); $BCD1=array('type' =>$row['type'], array( $k=>array('column1'=>$row['column1'],'column2'=>$row['column2'],'column3'=>$row['column3'],'column4'=>$row['column4'], 'column5'=>$row['column5'],'column6'=>$row['column6'],'column7'=>$row['column7']) )); $k++; } Hi guys, I'm still stuck on making this multi-level drop down menu, so I figure that I'll listen to how you guys would do it. I don't necessarily need any code, but just ideas on how to code it. Basically, I need it to store each item in a database. It needs to: be accessed, processed, and formatted with PHP end up returning either a multi-dimensional array, or the raw HTML. Examples: Code: [Select] <?php array( array( 'label'=>'Test', 'link'=>'index.php?r=test', 'sort'=>0, 'children'=>array(--blah blah blah--) ), array(--blah blah blah--) ); Code: [Select] <div id="menu"> <ul> <li><a href="index.php?r=test"><h2>Test</h2></a> <ul> <li><a href="blah">Blah</a> <ul> <li><a href="blah">Blah</a></li> </ul> </li> </ul> </li> </ul> </div> That's pretty much it. If you have any ideas or suggestions, please feel free to help me out. Thank you guys! I have the following code: Code: [Select] private function buildJSResponse(){ $data = ""; $i = 0; $arr = array(); while($this->db->row()){ $arr[] = (int)$this->db->field("average"); } $this->max = max($arr); $this->min = min($arr); $this->mid = round(($this->max + $this->min) / 2); foreach($arr as $val){ $nTime = ($val / $this->max) * 100; $data .= "data[$i] = ".$nTime.";"; $i++; } return $data; } It takes an array, finds the max/min and number halfway between the min/max. The next part I am not sure what to do. I am making a line graph using the canvas, so I am building a javascript array, which will contain the point on the chart. The problem I am having, is location. Lets say $max = 110, and $min = 95. the y position on the graph should be 0 for $max, and 100 for $min, then all the other points need to fall into their place as well. $nTime is supposed to do that, but it doesn't any suggestions? The attachment is the result I am getting from my above code. As you can see the lowest number is 49, so the value with 49 should touch the bottom, which it doesn't. |