PHP - How To Traverse Complex Directory
Hi, currently I have a function searchFolder that simply takes in ONE directory which holds all the xml files I wish to store to db via function writeXMLtoDBviaDOM.
I want to make it more robust(realistic) to be able to also search complex directories (so the main directory I pass as parameter to searchFolders) in turn holds sub-directory (which in turn holds further sub-directory) which finally holds all the xml files. here is code: Code: [Select] <?php $dir = "C:/dir/dir2/dir3/"; function searchFolders($dir) { $_filePath=""; $filePathsArray=array();//stores each file $xmlFiles = glob($dir . '*.xml'); if(is_dir($dir)) { // list files $xmlFiles = glob($dir . '*.xml'); //print each file name foreach($xmlFiles as $xmlFile) { print $xmlFile."<br />"; $filePathsArray[]=$xmlFile; } }//END BIG IF retreiving all files in dir param foreach($filePathsArray AS $curFile) { //set up db connection mysql_connect("localhost","root"); mysql_select_db("someDb"); $_filePath=$curFile; $dom=new DOMDocument(); $node=basename($_filePath);//$node is the file name only $dom->load($node); writeXMLtoDBViaDOM($dom->documentElement,$_filePath); }//END FOR-EACH LOOP for each XML file }//END FCN searchFolders VERSION 0 searchFolders($dir);//VERSION 0 ONLY searched 1 simple dir ?> Any help much appreciated! Similar TutorialsHi, starting at a given node, I want to be able to build a pathway from that current node all the way to the root node. Let's say I have this email.xml file: <?xml version="1.0" encoding="ISO-8859-1" ?> <email> <message> <to> <toFirstName>Bob</toFirstName> <toLastName type="common">Smith</toLastName> </to> </message> </email> Here is my script which btw is infinite loop: Code: [Select] <?php $doc=new DOMDocument(); $doc->load("email.xml"); $pathway=array(); $dom1=$doc->getElementsByTagName("toLastName")->item(0); while(!$dom1->documentElement->nodeName) { $pathway[]=$dom1->nodeName."/".$dom1->parentNode->nodeName."/"; $strPathway=implode("",$pathway); print $strPathway; } ?> The output I want is in this format: email/message/to/toLastName (I will figure out how to use rsort since in the while loop it appends as: toLastName/to/message/email Any help much appreciated! Hi there, How could I get the value of every 4 bytes of a BLOB? Additionally, how can I add an item to the end of a BLOB and store it back in the database? Cheers, George Hi guys, I've been working on a script for a while now, and I'm sure it doesn't look great and all, and it's probably really messed up.. But right now I've finally got it working! There's only 1 thing I'd really like to add.. Searching through & listing of remote directories! The directories I'm trying to list have directory listings enabled, and I think it *should* be possible. I just have no clue how. Here's my current code in a beautiful mix of HTML and PHP: <? $border_size = "0"; function returner($what) { $what=explode("/",$what); $tps=count($what); $what=$what[$tps-1]; return $what; } $page_url= ""; $home_url=returner(__FILE__); if(isset($_GET['q'])) { $qtext=$_GET['q']; } else { $qtext=""; } function getdirsize($directory, $format=FALSE) { $size = 0; if(substr($directory,-1) == '/') { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return -1; } if($handle = opendir($directory)) { while(($file = readdir($handle)) !== false) { $path = $directory.'/'.$file; if($file != '.' && $file != '..') { if(is_file($path)) { $size += filesize($path); } elseif(is_dir($path)) { $handlesize = getdirsize($path); if($handlesize >= 0) { $size += $handlesize; } else { return -1; } } } } closedir($handle); } if($format == TRUE) { if($size / 1048576 > 1) { return round($size / 1048576, 1).' MB'; } elseif($size / 1024 > 1) { return round($size / 1024, 1).' KB'; } else { return round($size, 1).' bytes'; } } else { return $size; } } if(isset($_GET['type'])){ $type=$_GET['type']; } else { $type="new"; } $textures=0; $models=0; $avatars=0; $seqs=0; $sounds=0; foreach (glob("textures/*.jpg") as $texture){ $textures++; } foreach (glob("models/*.zip") as $model){ $models++; } foreach (glob("avatars/*.zip") as $avatar){ $avatars++; } foreach (glob("seqs/*.zip") as $seq){ $seqs++; } foreach (glob("sounds/*.zip") as $sound){ $sounds++; } ?> <!DOCTYPE html> <html> <head> <title>ObjectPath Search</title> <style type="text/css"> #wrapper { width: 850px; margin: 30px auto 30px auto; padding: 10px; } body { color:#C6C6C6; background:#1E1E1E; /* margin:0; padding:0; */ overflow-x:hidden; } #tabs { font: 85% "Trebuchet MS", sans-serif; } .left { float: left; } .right { float: right; } a:link, a:visited, a:active { color: #3DB015; text-decoration: none; } a:hover { color: #00E0FF; } h2 { color: #3DB015; padding-bottom: 0.2em; font-size: 110%; } ul#icon {margin: 0; padding: 0;} ul#icon li {margin: 1px; position: relative; padding: 1px 0; cursor: pointer; float: left; list-style: none;} ul#icon span.ui-icon {float: left; margin: 0 1px;} </style> <link type="text/css" href="http://objects.jk-hosting.com/search/css/black-tie/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-ui-1.8.2.custom.min.js"></script> <script type="text/javascript"> function formHandler(form){ var URL = document.form.site.options[document.form.site.selectedIndex].value; window.location.href = URL; }; $(function(){ // Tabs $('#tabs').tabs(); }); </script> </head> <body> <div id="wrapper"> <div id="tabs"> <!-- Tabs start --> <ul> <li><a href="#tab-search">Search</a></li> <li><a href="#tab-list">List Objects</a></li> <li><a href="#tab-info">OP info</a></li> </ul> <div id="tab-search"><!-- Searchtab start --> Please enter a string to search for, and choose a folder to search in. <br /><br /> <form name="Search"> <input type='hidden' value='search' name='type'> <input value='<? print $qtext; ?>' type='text' name='q'> <select name='map'> <option selected='selected' value='models'>Models</option> <option value='avatars'>Avatars</option> <option value='textures'>Textures</option> <option value='seqs'>Seqs</option> <option value='sounds'>Sounds</option></select> <input type='submit' value='Search'> </form> </div> <!-- Searchtab end --> <div id="tab-list"><!-- Listtab start --> Please pick a folder to browse. <br /><br /> <form name="form"> <select name="site" onChange="javascript:formHandler()"> <option value="#">Look in folder...</option> <option value="<? print $page_url; ?>?type=list&map=models">Models</option> <option value="<? print $page_url; ?>?type=list&map=avatars">Avatars</option> <option value="<? print $page_url; ?>?type=list&map=textures">Textures</option> <option value="<? print $page_url; ?>?type=list&map=seqs">Seqs</option> <option value="<? print $page_url; ?>?type=list&map=sounds">Sounds</option> </select> </form> </div> <!-- Listtab end --> <div id="tab-info"><!-- Info tab start --> The OP currently contains: <br /><br /> <table> <tr><td><b><? echo $models; ?></b></td> <td>Models</td></tr> <tr><td><b><? echo $avatars; ?></b></td> <td>Avatars</td></tr> <tr><td><b><? echo $textures; ?></b></td> <td>Textures</td></tr> <tr><td><b><? echo $seqs; ?></b></td> <td>Seqs</td></tr> <tr><td><b><? echo $sounds; ?></b></td> <td>Sounds</td></tr> </table> </div> <!-- Info tab end --> </div> <!-- Tabs end --> </div> <!-- Start PHP generated content --> <? if($type=="search" || $type=="list") { $M=$_GET['map']; if($type=="search") { $Q=$_GET['q']; $empty="Nothing found with <b>\"" . $Q . "\"</b> in it's name.<br />\nPlease make a more general search query, or try a different folder.\n\n"; } else { $Q=""; $empty='This folder is empty'; } if($M=="textures") { $ext="jpg"; } else { $ext="zip"; } $i=0; print "<hr>\n"; $endfile=array(); $endsize=array(); $endsize2=array(); foreach (glob($M."/*".$Q."*.".$ext) as $filename) { $filename = explode(".", $filename); $filename=$filename[0]; $filename = explode("/", $filename); $filename=$filename[1]; $i++; $endfile[$i]=$filename; if($ext=="jpg") { $endfile[$i]="<a name='".$endfile[$i]."' href='".$pageurl."?type=view&name=".$endfile[$i]."&folder=".$M."&from=".$type."&addon=".$Q."'>".$endfile[$i]."</a>"; } $endsize[$i]=$size; $endsize2[$i]=$size2; } if($i != 1) { print "<b>".$i."</b> items were found.\n<hr>\n"; } else { print "<b>".$i."</b> item was found.\n<hr>\n"; } echo("<table width='100%' border='" . $border_size . "' cellspacing='0' cellpadding='0' >\n"); if($i!=0) { for ($t = 1; $t < $i; $t++) { $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } if($t=="1") { echo("<tr><td width='10%'>Number</td><td width='3%'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></td><td width='60%'>Name</td></tr>\n"); } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); flush(); } $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); } print "</table>\n"; if($i=="0") { print $empty; } } elseif($type=="view") { $filename=$_GET['name']; $folder=$_GET['folder']; if($_GET['from']=="list"){ $addon="?type=list&map=".$folder."#".$filename; } if($_GET['from']=="search"){ $addon="?type=search&q=".$filename."&map=".$folder."#".$filename; } print"<center><a href='".$home_url."'>Home</a></center>"; print "<hr>\n<center><img src='".$folder."/".$filename.".jpg'></img></center>\n<hr>\n<br />\n<a href='".$page_url."".$addon."'>Previous Page</a>\n"; } $htmlshow=""; if($_GET['type']=="returnOPfile") { if(isset($_GET['split'])) { $splitter=$_GET['split']; } else { $splitter=" | "; } if(isset($_GET['html'])) { $htmlshow="<br />"; } foreach (glob("textures/*.jpg") as $texture){ if(isset($_GET['size'])) { $size=$splitter.filesize($texture); } $texture = explode("/", $texture); $texture=$texture[1]; print "textures".$splitter.$texture.$size."\n".$htmlshow; } foreach (glob("models/*.zip") as $model){ if(isset($_GET['size'])) { $size=$splitter.filesize($model); } $model = explode("/", $model); $model=$model[1]; print "models".$splitter.$model.$size."\n".$htmlshow; } foreach (glob("avatars/*.zip") as $avatar){ if(isset($_GET['size'])) { $size=$splitter.filesize($avatar); } $avatar = explode("/", $avatar); $avatar=$avatar[1]; print "avatars".$splitter.$avatar.$size."\n".$htmlshow; } foreach (glob("seqs/*.zip") as $seq){ if(isset($_GET['size'])) { $size=$splitter.filesize($seq); } $seq = explode("/", $seq); $seq=$seq[1]; print "seqs".$splitter.$seq.$size."\n".$htmlshow; } foreach (glob("sounds/*.zip") as $sound){ if(isset($_GET['size'])) { $size=$splitter.filesize($sound); } $sound = explode("/", $sound); $sound=$sound[1]; print "sounds".$splitter.$sound.$size."\n".$htmlshow; } } ?> <!-- End PHP generated content --> </body> </html> So right now my question to you PHP freaks is, can you please help me edit my script so I can search through a remote directory? *This* is one of the directories I wish to be able to search through & list.. Thanks in advance. Edit; It might help if you know what the site currently looks like. *Click* i have made an delete files script which works for only one directory but not sub directory so i want to delete files of same extention from directory and subdirectory. My current code is Code: [Select] <? $dir = 'hmm/'; function scanr($dir){ $arr = glob($dir.'/*.jpg'); foreach($arr as $vv){ //check if $vv is a file if(is_file($vv)){ //if file, get the filename $vx=explode('/',$vv); $file=$vx[count($vx)-1]; // if no extension delete the file unlink($vv); // print the deletion message echo $vv." deleted!<br>";}else{ // if $vv is a dir then scan it again for files scanr($vv); }} } scanr($dir); ?> Well, as i said in my previous post, im pretty new into php, mysql, i was searching into how to make queries but i can't find where to learn doing real complex ones. This is how it goes, -i've got an array full of id's -inside my table i wan't to get all the values where folder_id == to any id inside my array(i guess a loop would do this) -and i wan't to get only the first 20 values of the columns (folder_id and photo) for every folder_id any suggestions? thanks This is the array Array (2) ( | ['0'] => Array (6) | ( | | ['name'] = String(7) "Pikemen" | | ['hp'] = Integer(3) 100 | | ['atk'] = Integer(1) 5 | | ['def'] = Integer(1) 5 | | ['rng'] = Integer(2) 15 | | ['amt'] = Integer(2) 30 | ) | ['1'] => Array (6) | ( | | ['name'] = String(8) "Champion" | | ['hp'] = Integer(3) 150 | | ['atk'] = Integer(1) 8 | | ['def'] = Integer(1) 6 | | ['rng'] = Integer(1) 5 | | ['amt'] = Integer(2) 10 | ) ) I have an attack value ( say 300 ). I want to take this value and minus the first key amount $array[0]['amt']. If that value then comes to 0 I then want to skip to the next array key and do the same $array[1]['amt'] until the attack value runs out or every array keys amount is equal to 0. Any ideas? Greetings - So I have an issue with my form right now which can be found he http://youawfulme.com/Form.html If you look, you will see two expanding columns under Providers and References. The HTML code for them to expand looks like this: Quote <span class="duplicateSpan"><a id="tfa_0583059728034-wfDL" class="duplicateLink" href="#">Next Provider</a></span> and the PHP code that handles their database storage looks like this: Quote // Insert Providers.. if(count($_POST['tfa_FirstName1']) > 1) { for($i = 0; $i < count($_POST['tfa_FirstName1']); $i++) { $tmpsql = "INSERT INTO tmpProviders (tmpId,FirstName,LastName,LicenseType,PrimarySpecialty,SecondarySpecialty,NYStateLicenseNum,DEANumber,NPINumber,EmailAddress,DaysPerWeek,PrimaryCareProv) VALUES ($oldid,'" . $_POST['tfa_FirstName1'][$i] . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_LastName1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_LicenseType1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_PrimarySpecialty1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_SecondarySpecial'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NYStateLicenseNu1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DEANumber1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NPINumber1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_EmailAddress1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DaysPerWeek1'][$i]) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d+/","\\1",$_POST['tfa_Ifthisindividual'][$i]) . "');"; mysql_query($tmpsql); } } else { $tmpsql = "INSERT INTO tmpProviders (tmpId,FirstName,LastName,LicenseType,PrimarySpecialty,SecondarySpecialty,NYStateLicenseNum,DEANumber,NPINumber,EmailAddress,DaysPerWeek,PrimaryCareProv) VALUES ($oldid,'" . $_POST['tfa_FirstName1'] . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_LastName1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_LicenseType1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_PrimarySpecialty1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d*/","\\1",$_POST['tfa_SecondarySpecial']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NYStateLicenseNu1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DEANumber1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_NPINumber1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_EmailAddress1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_/","",$_POST['tfa_DaysPerWeek1']) . "'"; $tmpsql = $tmpsql . ",'" . preg_replace("/tfa_([a-zA-Z]+)\d+/","\\1",$_POST['tfa_Ifthisindividual']) . "');"; mysql_query($tmpsql); } if(count($_POST['tfa_PracticeName']) > 1) { At this moment, when you fill out my form, all of the information saves to three separate tables. The Provider input goes into a temporary providers table, the Referrals to a temporary Referral , and the rest of the data to a temporary information table. Once the user submits the application, the temporary tables are cleared after having been moved to permanent tables (Still three tables) My goal is for all of these values to save to one table, whether it be from three separate temps to one final or one temp to one final. My programmer was having trouble figuring it out and kind of left me on my own.. I really need some help The Providers and Reference tables are done in such a way that if there are more than one entry, it will create a new row for each entry with a new ID number but the same "tempid" number, the latter matching the ID number in the main information table. Can I have it such that PHP will check to see if the tempIDs match, and if they do, move the information into new columns on the same row? So that way, instead of having say 3 different IDs with one temp ID for three different providers.. instead have that information all placed on one row, with one ID, and new columns? In my head, I figured I would expand my table 5x. If I have five columns now, I will have 25 after. For each "Provider Name", I will now have "Second Provider Name", "Third Provider" name, etc... If the user only adds one provider, these won't be used. If they had multiples, up to five, the info will be placed into these new columns. I just can't get this to work.. When I expand the column and inspect the element in HTML, it says, for example, Provider[1] and Provider[2] .. Incrementing in brackets for each addition. But if I try to, say Quote $SecondProviderName = $_POST['tfa_ProviderName[2]']; .. It simply doesn't work. Sorry for all this, I just need some help and so far you guys have been a great resource. Thank you Hi everyone, I'm still kind of a noob when it comes to PHP although i am learning more when i can. I'm in the middle of creating an affiliate system in PHP/MySQL and as you'll be able to tell from looking at my code I'm no expert in it and no doubt what I've created can be done in a more efficient way. This is where i need your help, for 2 different reasons, one to guide/help me re-create my script the way you would do so. The second thing i need help with is (EDIT: i think we'll concentrate on re-creating the script first of all). //BEGIN GETTING BRAND NAMES $connection = mysqli_connect( "$connectip", "$swiftuser", "$swiftpass", "$swiftdb" )or die( "Error " . mysqli_error( $connection ) ); $sql = "SELECT Name, ProgramID FROM programs WHERE Status='1'"; $result = mysqli_query( $connection, $sql )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $result->num_rows > 0 ) { while ( $row = $result->fetch_assoc() ) { $ProgramID = $row[ "ProgramID" ]; //BEGIN GETTING CLICKS THAT MONTH FOR THE BRAND $startmonth = date( 'Y-m-d', strtotime( 'first day of this month' ) ); $endmonth = date( 'Y-m-d', strtotime( 'last day of this month' ) ); $todaysdate = date( 'Y-m-d' ); $sqlclicks = "SELECT COUNT(*) AS 'TotalMonth' FROM `clicks` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND DATE(Timestamp) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlclicks; $resultclicks = mysqli_query( $connection, $sqlclicks )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultclicks->num_rows > 0 ) { while ( $rowclicks = $resultclicks->fetch_assoc() ) { $clicks = $rowclicks[ "TotalMonth" ]; } } else { $clicks = "0"; } //END GETTING CLICKS THAT MONTH FOR THE BRAND //BEGIN GETTING REGISTRATIONS THAT MONTH FOR THE BRAND $sqlreg = "SELECT COUNT(*) AS 'TotalReg' FROM `players` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND DATE(SignupDate) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlclicks; $resultreg = mysqli_query( $connection, $sqlreg )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultreg->num_rows > 0 ) { while ( $rowreg = $resultreg->fetch_assoc() ) { $reg = $rowreg[ "TotalReg" ]; } } else { $reg = "0"; } //END GETTING REGISTRATIONS THAT MONTH FOR THE BRAND //BEGIN GETTING FTDs THAT MONTH FOR THE BRAND $sqlftd = "SELECT COUNT(*) AS 'TotalFTDs' FROM `players` WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND FTDmatched ='1' AND DATE(FTDmatchedDate) BETWEEN '$startmonth' AND '$endmonth' "; //echo $sqlftd; $resultftd = mysqli_query( $connection, $sqlftd )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultftd->num_rows > 0 ) { while ( $rowftd = $resultftd->fetch_assoc() ) { $ftds = $rowftd[ "TotalFTDs" ]; } } else { $ftds = "0"; } //END GETTING FTDs THAT MONTH FOR THE BRAND //BEGIN CPA COMMISSION THAT MONTH FOR THE BRAND $sqldeal = "SELECT DealID AS `DealID`, SUM(CASE WHEN FTDmatched = '1' THEN 1 ELSE 0 END) AS `TotalFTDs` FROM players WHERE AffID = '$AffID' AND ProgramID = '$ProgramID' AND `FTDmatchedDate` BETWEEN '$startmonth' AND '$endmonth' GROUP BY DealID"; //echo $sqldeal; $resultdeal = mysqli_query( $connection, $sqldeal )or die( "Error in Selecting " . mysqli_error( $connection ) ); $dealid = array(); $dealftds = array(); $i = 0; if ( $resultdeal->num_rows > 0 ) { while ( $rowdeal = $resultdeal->fetch_assoc() ) { $dealid[ $i ] = $rowdeal[ "DealID" ]; $dealftds[ $i ] = $rowdeal[ "TotalFTDs" ]; $i = $i + 1; } } else { $commissionftd = "0.00"; } $totaldeals = count( $dealid ); //echo "<br>"; //echo "Total Deals for Affilaite is: " . $totaldeals; $sqlpayout = array(); $totalcpa = array(); for ( $tt = 0; $tt < count( $dealid ); $tt++ ) { $sqlamount = "SELECT CPA AS `CPAAmount` FROM affDeals WHERE AffID = '$AffID' AND `affDealID` = '$dealid[$tt]' AND `Type` = 'CPA' AND `StartDate` <= '$todaysdate' AND `EndDate` >= '$todaysdate' OR AffID = '$AffID' AND `affDealID` = '$dealid[$tt]' AND `Type` = 'Hybrid' AND `StartDate` <= '$todaysdate' AND `EndDate` >= '$todaysdate'"; //echo "<br>" . $sqlamount . "<br>"; $resultamount = mysqli_query( $connection, $sqlamount )or die( "Error in Selecting " . mysqli_error( $connection ) ); if ( $resultamount->num_rows > 0 ) { while ( $rowamount = $resultamount->fetch_assoc() ) { $sqlpayout[ $tt ] = $rowamount[ "CPAAmount" ]; $totalcpa[ $tt ] = $sqlpayout[ $tt ] * $dealftds[ $tt ]; } } else { $sqlpayout[ $tt ] = "0.00"; } } //END CPA COMMISSION THAT MONTH FOR THE BRAND $totalcommission = array_sum( $totalcpa ); echo '<tr> <td>' . $row[ "Name" ] . '</td> <td>' . $clicks . '</td> <td>' . $reg . '</td> <td>' . $ftds . '</td> <td>£' . $totalcommission . '</td> </tr>'; } } else { echo "0 results"; } //END GETTING BRAND NAMES ?> I've also attached the SQL tables, the table Affiliates is just the structure so you will need to add a record in there. All other tables have data in them for you to work with. EDIT: since i cant upload SQL files on here you can download them he https://ufile.io/gnoqf I find it a lot easier for me to learn PHP by trying to create stuff myself, then if i need help i do some research on how to achieve what I'm trying to code and if i fail i keep trying to doing more research until it works. I also ask other PHP developers for advice and help and if they provide me with examples then again that helps me learn a lot better and quicker as i can see first hand how its supposed to look and how it works. I apologise for my messy coding but like i said I'm still learning PHP, if anyone could help me re-create my script more efficiently I'd very much appreciate that. Maybe I've done too much code and certain MySQL queries can be done in just 1 MySQL Query instead of multiple ones, i don't know and that's why I'm here asking for help/advice to help me learn more. Anyway thank you in advance and if you'd like to know any information please let me know. Hi,
Is it possible to create an web-page,form,that would accept specific input and generate Xojo or Php for this could be used, below is the sample XML file and Data Format.
<?xml version="1.0" encoding="UTF-8" ?>
If Yes, then how to write the desired PHP code to solve this problem?
Thanks Hi, I have got some data out of my database, I would now like to sort all of this by putting the data into arrays, something looking like this: branch - costs - profit France - 406.85 - 1392.48 So each branch is one item in the array, but has the costs and profit with it too. I would then like to sort those arrays by things like branch name, costs and profit. Is this possible? Hi I have an array from an sql query and i would like to eliminates all the duplicates, i have google search for an answer without success, any help would be aprecciated $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $final = array(); $json = array(); if ($idCoord > 0 || $isDirecao > 0) { foreach ($result as $row) { $idAtividade = $row['idAtividade']; if (!isset($final[$idAtividade])) { $final[$idAtividade]['Escola'] = $row['Escola']; $final[$idAtividade]['Atividade'] = $row['Atividade']; $final[$idAtividade]['Periodo'] = $row['Periodo']; $final[$idAtividade]['Mes'] = $row['Mes']; $final[$idAtividade]['haveClasses'] = $row['haveClasses']; $final[$idAtividade]['DataPrevista'] = $row['DataPrevista']; $final[$idAtividade]['Destinatarios'] = $row['Destinatarios']; $final[$idAtividade]['Orcamento'] = $row['Orcamento']; $final[$idAtividade]['Organizador'] = $row['Organizador']; $final[$idAtividade]['Obs'] = $row['Obs']; $final[$idAtividade]['PdfAtividade'] = $row['PdfAtividade']; $final[$idAtividade]['Avaliacao'] = $row['Avaliacao']; $final[$idAtividade]['idProfessor'] = $row['idProfessor']; $final[$idAtividade]['PdfAvaliacao'] = $row['PdfAvaliacao']; $final[$idAtividade]['Validado'] = $row['Validado']; $final[$idAtividade]['Nome'] = array(); $final[$idAtividade]['Grupo'] = array(); $final[$idAtividade]['Departamento'] = array(); } $final[$idAtividade]['Nome'][] = $row['Nome']; $final[$idAtividade]['Grupo'][] = $row['Grupo']; $final[$idAtividade]['Departamento'][] = $row['Departamento']; } foreach ($final as $idVisita => $reservation) { $json[] = $reservation; } } echo json_encode($json); } And this is an example i'm receiving
So you can see that Grupo has 4 times the value "500" and Departamento has 4 times that string... How can avoid this and have only one value of each?
Thanks
Hi guys, I need to find a way to do the following in this string: Code: [Select] {"id":"51","value":["Lorem Ipsum","Lorem Ipsum","new"]} I need to match Code: [Select] "id":"51" If that is matched, I want to remove that ENTIRE string. How would I go about doing that? In other words, I run a preg_match or something like that and if "id":"51" is found, i need to remove the entire element in which it is contained. In this case the element is the above mentioned string. Any ideas? Perhaps with RegEx? (I have no clue how to use RegEx) Hey. I am not 100% with it at the moment, bit under the weather. (If you ask why I am working, your not a developer) Sob story aside (excuses really) Basically I have built a function to manipulate BB Code to HTM I wrote it, looked back at it and thought, my god this looks overly complex for this sort of thing. It works but just seems like a lot of wasted code. Please help me narrow this down public function BB2HTM($str){ /* Valid BB Code [b] / [/b] = STRONG [i] / [/i] = Italic [u] / [/u] = Underline [url=http://www.example.com]My Example[/url] = A Link [size=X]bla[/size] = Change font size where X is percentage of actual size, default options 50=>small, 100=>normal, 200->large [list]bla[/list] Handles Unordered Lists, with New Line being new list item [list=X]bla[/list] Handles Ordered List, where X is start number, again New Line is New List item */ /* First, we will do the basics, with a simple str_replace */ $str = nl2br($str); $arrBBCode = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]'); $arrHTMCode = array('<strong>', '</strong>', '<i>', '</i>', '<u>', '</u>'); $str = str_replace($arrBBCode, $arrHTMCode, $str); // /* Now we want to handle a URL, open in new window */ $regexURLPattern = '#(\[url\=(.*))(\])(.*?)(\[/url\])#is'; preg_match_all($regexURLPattern, $str, $arrMatches); /* Loop through the results, build a valid HTM link and replace what we found with the correct format */ for($i = 0; $i < count($arrMatches[0]); $i++){ $strNewLink = '<a href="'.$arrMatches[2][$i].'" target="_blank">'.$arrMatches[4][$i].'</a>'; $str = str_replace($arrMatches[0][$i], $strNewLink, $str); } /* End Handle URL */ /* Now font size. User can maniplate the number on size so we want to check for this and limit, so someone dont put 1% and hide stuff or 10000% and break the website */ $regexSizePattarn = '#(\[size=)([0-9]*)(\])#'; preg_match_all($regexSizePattarn, $str, $arrMatches); /* Loop through the results, put a check on the number */ for($i=0; $i < count($arrMatches[0]); $i++){ if($arrMatches[2][$i] > 200){ $arrMatches[2][$i] = 200; }elseif($arrMatches[2][$i] < 100){ $arrMatches[2][$i] = 100; } /* Change it and close the tag, keep the str_replace with the opener for later editing / auditing */ $strFontTag = '<span style="font-size:'.$arrMatches[2][$i].'%">'; $str = str_replace($arrMatches[0][$i], $strFontTag, $str); } $str = str_replace('[/size]', '</span>', $str); /* End Handle Size */ /* Is it a list, What list, where to start */ $regexListPattern = '#(\[list)(=?)([0-9]*)?(\])(.*?)(\[/list\])#is'; preg_match_all($regexListPattern, $str, $arrMatches); /* Loop through our results */ for($i = 0; $i < count($arrMatches[0]); $i++){ $strLstItems = ''; /* Is it unordered or Ordered? Where do we start, 1 or 100 Add our closing tag here as well in variable, save doing this again*/ if($arrMatches[3][$i] != ''){ $strEndLst = '</ol>'; if($arrMatches[3][$i] > 1){ $strLstItems = '<ol start="'.$strLstItems[3][$i].'">'; }else{ $strLstItems = '<ol>'; } }else{ $strEndLst = '</ul>'; $strLstItems = '<ul>'; } /* We can split the New lines as we done nl2br() as the top, we split on br */ $arrListItems = split("<br />", $arrMatches[5][$i]); for($x = 0; $x < count($arrListItems); $x++){ /* We dont want empty items, where people double enter or something */ if($arrListItems[$x] != ''){ $strLstItems .= '<li>'.$arrListItems[$x].'</li>'; } } /* Close the item as set above and replace it in our main str */ $strLstItems .= $strEndLst; $str = str_replace($arrMatches[0][$i], $strLstItems, $str); } /* End Handle Lists */ return $str; } Hi; i would like to search for a regular expression to grab all printf occurences including the folowing senarios :
printf("something"); printf("something", variables); printf("something", variables, variables); printf("something);something", variables, variables);To simplify the third and fourth cases, the regex should start from printf(" and go intil it find ); with a white space after it. But i didn't realise how to do it. This trick should work also for the first and second case. Thanks Edited by Dareros, 26 September 2014 - 01:27 PM. I am so over my head right now that I don't even know where to begin asking for help?! (This is regarding a Form which ask 10 Questions and then captures and processed up to 10 Answers.) Originally, I had an answerArray where I captured and process all User Answers to Questions, and all was beautiful in the universe! Then after being 95% done, I got the - not so brilliant - idea of dynamically generating my Q&A Form with Questions being pulled from the question table (along with Answers from the answer table). Based on a recommendation from gizmola (??), I created a SECOND Question & Answer multidimensional array - thoughtsArray - which pulled together the Questions and Answers. This made sense, because it is easier to populate the Form when the dataset is coming all from one place. The problem is two-fold at this point... 1.) Is it a good or bad design to have answerArray to capture and process Form inputs, and then a thoughtsArray for display purposes?? 2.) How do I design a Form which allows both my multidimensional thoughtsArray and my one-dimesnional answerArray to plug into it, specifically the name attribute?? Here was my original array... foreach($_POST['answerArray'] as $q => $a){ // Copy data from POST to PHP array. $answerArray[$q] = trim($a); if (strlen($answerArray[$q]) > 1024){ // Invalid Answer. $errors[$q] = 'Answer cannot exceed 1024 characters.'; } }//End of VALIDATE FORM DATA And here is my new display array... // Populate PHP array with Questions & Answers. $x=1; while (mysqli_stmt_fetch($stmt7)){ $thoughtsArray[$x] = array('questionID' => $questionID, 'questionText' => $questionText, 'answerText' => $answerText); $x=$x+1; } Here is how my original - pre automation - Form looked... <!-- Question 1 --> <label for="question1">1.) Why did you decide to start your own business?</label> <textarea id="question1" name="answerArray[1]" cols="60" rows="2"><?php if (isset($answerArray[1])){echo htmlentities($answerArray[1], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors[1])){ echo '<br /><span class="error">' . $errors[1] . '</span>'; } ?> And here is my new Form - which works for displaying, but is now broken for processing... <?php foreach($thoughtsArray as $questionNo => $qaArray){ // Build Question. echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . "\n"; // Build Answer. echo '<textarea id="question' . $questionNo . '" name="' . $qaArray["questionID"] . '" cols="60" rows="2">'; echo (isset($questionNo) ? htmlentities($qaArray['answerText'], ENT_QUOTES) : ''); echo "</textarea>\n\n"; } ?> Hope that all makes sense?! Debbie I'm trying to echo the directory and sub directory only. I am not looking to show the files contained - only folders. Phew, okay, I'm at my wits end on how to accomplish this task. My client wants a forum program, but she wants it different from normal in that the forum page won't show just the main threads where you would have to click to see the replies, etc - she wants the forum page to display threads and replies in a tiered fashion. Something like this: Code: [Select] - Thread 1 - Reply 1-1 - Reply 1-1-1 - Reply 1-2 - Reply 1-3 - Reply 1-3-1 - Reply 1-3-1-1 - Reply 1-3-1-1-1 - Reply 1-3-1-2 - Reply 1-3-2 - Thread 2 - Thread 3 - Reply 3-1 etc So, the threads should be arranged in order of their property timeLastChanged (which is updated on replies to it, replies to replies of it, edits, etc) which produces the "bumping" functionality. Then the replies under it should be arranged in order of their property timeStarted (which is the timestamp of when it got created). Now, I have the script so far to the point where I have 3 arrays of objects (stickyObjs, mainsObjs, replyObjs) and these objects are instances of Post with their properties being their database values (author, timeStarted, subject, etc). Now, I have thought to arrange these arrays into one big array of objects in the order that they should appear on the page (don't worry about the indent, that's done elsewhere.) Anyway, how would I go about sorting these arrays into one big array of objects in the order they should appear with those two sorting criteria above (sorting criteria is stickies, 1st main in the order of last available timeLastChanged, any replies to mains, replies to replies, ad nauseum in order of timeStarted, then the next main in the order of timeLastChanged, etc.) I have gone through many possible ways, all of which are incredibly complex and involve many copies of arrays and pointers to objects in arrays and iteration counters and GAH! Does anyone know of an easy way to accomplish this sorting? Here is what I have so far: Code: [Select] class Category { public $title; public $majCatID; public $catID; public $modLevel; public $postingLevel; public $hostedByUID; public $order; public $shortName; public $info; public $stickyObjs; public $mainsObjs; public $replyObjs; private $database; public function __construct($catID) { $this->database = new TBDatabase; $result = $this->database->getIntRow(CAT_TABLE, 'catID', $catID); $row = $this->database->fetchAssoc($result); $this->title = $row['title']; $this->majCatID = $row['majCatID']; $this->catID = $row['catID']; $this->modLevel = $row['modLevel']; $this->postingLevel = $row['postingLevel']; $this->hostedByUID = $row['hostedByUID']; $this->order = $row['order']; $this->shortName = $row['shortName']; $this->info = $row['info']; $this->pointer = 0; } public function sortPosts() { $table = $this->shortName."_threads"; $this->getStickyObjs(); $numStickies = count($this->stickyObjs); $this->getMainObjs(); $numMains = count($this->mainsObjs); $this->getReplyObjs(); $numReplies = count($this->replyObjs); } private function getStickyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isSticky = 1"); if (!$result) { $this->stickyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->stickyObjs[$i] = new Post($row); $i++; } return; } private function getMainObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply = 0"); if (!$result) { $this->mainsObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->mainsObjs[$i] = new Post($row); $i++; } return; } private function getReplyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply != 0"); if (!$result) { $this->replyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->replyObjs[$i] = new Post($row); $i++; } return; } } Thanks! Ok it's abit complicated so i'll try to explain as best as I can. Upon registration a file is created with your username that was registered and also a file for your profile named after your username so it would be /profiles/usernamesprofilehere.php. I put a code into the profile that is: Code: [Select] include ("/home/giacjrdi/public_html/mysite/profiles/profileinfo/$username.info.php"); echo "<center><b><br /> $user's Profile <br /></b></center>"; $username is calling the cookie's username while $user is calling the account's username. eg if I try to view "bob"'s profile but logged in as "fred" since the include function is under $username which is cookies, it will retrieve "fred"'s information and post it on "bob"'s profile. The only sollution i can think of would be to store a username variable in the url and use it for the include function. Hiya, I was cruising along with SOAP nicely until I needed to parse more complex xml in a soapcall. I am using non-wdsl if that makes any difference. I need to create XML in the following structu Code: [Select] <Body> <SOAP_updateCreateContactMarketingRule> <Contact_ID xsi:type="xsd:int">1</Contact_ID> <MarketingRule_ID xsi:type="xsd:int">1</MarketingRule_ID> <MarketingQuestions> <MarketingQuestion> <MarketingQuestion_ID xsi:type="xsd:int">1</MarketingQuestion_ID> <Answer xsi:type="xsd:string">No</Answer> </MarketingQuestion> <MarketingQuestion> <MarketingQuestion_ID xsi:type="xsd:int">2</MarketingQuestion_ID> <Answer xsi:type="xsd:string">Yes</Answer> </MarketingQuestion> </MarketingQuestions> </SOAP_updateCreateContactMarketingRule> </Body> So, I set my parameters up as follows: $params[] = new SoapParam("1", "Contact_ID"); $params[] = new SoapParam("1", "MarketingRule_ID"); $params[] = new SoapParam(array("MarketingQuestion"=>array("MarketingQuestion_ID"=>1, "Answer"=>"Yes")), "MarketingQuestions"); And I am getting the following XML generated when I use __getLastRequest() Code: [Select] <SOAP-ENV:Body> <ns1:SOAP_updateCreateContactMarketingRule> <Contact_ID xsi:type="xsd:string">1</Contact_ID> <MarketingRule_ID xsi:type="xsd:string">1</MarketingRule_ID> <MarketingQuestions SOAP-ENC:arrayType="ns2:Map[1]" xsi:type="SOAP-ENC:Array"> <item xsi:type="ns2:Map"> <item> <key xsi:type="xsd:string">MarketingQuestion_ID</key> <value xsi:type="xsd:int">8</value> </item> <item> <key xsi:type="xsd:string">Answer</key> <value xsi:type="xsd:string">Yes</value> </item> </item> </MarketingQuestions> </ns1:SOAP_updateCreateContactMarketingRule> </SOAP-ENV:Body> Clearly my third parameter is not set up correctly - can anyone help with this? Thanks This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306845.0 |