PHP - Need Some Logic For A Simple Problem
hi guys
usename:password user1:pass1 user2:pass2 user3:pass2 i have a function fun(username,pass) and i want to run it for lots of different user names and passwords. what would the best way to do this? would i make an array and use a foreach loop or how would i do it and what could would i need?? Similar TutorialsI'm building a query that searches by database and returns matching (or almost matching) terms. That part isn't the problem- I have it up and working. The problem is that I'm trying to narrow down the search results, and it's not working. Here's the query that works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); Here's the query that DOESN'T works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE type='Cars' AND name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); What I'm trying to do is say "give me all the results from type:Cars. Instead, it ignores the WHERE type='Cars' statement, and returns results for all types. It frustrates me because I use the same exact query in a thousand other places, and it works everywhere else. For example: Code: [Select] $sql = "SELECT * FROM auctions WHERE type='Boats' AND state='$v4' ORDER BY $v1 $v2"; works just fine. I'm not exactly an expert on any of this, but I can see no logical reason why this works, but the Search code doesn't. They appear in all ways identical, at least as far as query structure goes. Can anyone spot where I screwed up? Thanks! Kyle So the code works right, (I think) but for some reason the way I built it the logic comes back null. I can do All w a specific shift/s, and All with department/s but I can't do All shifts and All departments it doesn't' error either, just brings back nothing, maybe timing out? I'm very new at this so I apologize in advance. Code below ############################################################ <form method="post" action=""> <br><br> <table bordercolor="yellow" border="2"> <tr><td class="line"><b>Start Date:</b></td><td> <input type="text" name="startdate" value="mm/dd/yyyy" /></td></tr> </tr> <tr><td class="line"><b>End Date:</b></td><td> <input type="text" name="enddate" value="mm/dd/yyyy" /></td></tr> </tr> <tr><td class="line"><b>Shift:</b></td><td> <SELECT NAME="shift" > <option selected>Select Shift</option> <option>First</option> <option>Second</option> <option>Third</option> <option>All</option> </SELECT> </td></tr> <tr><td class="line"><b>Department:</b></td><td> <SELECT NAME="department" > <option selected>Select Department</option> <option>Advanced Hosting Support</option> <option>Server Support</option> <option>Managed Support</option> <option>All</option> </SELECT> </td></tr> </tr> </tr> </table> <br><br> <input type="submit" value="submit" /> </form> <form action="" method="post"> </form> </html> <?php require_once('global.inc.php'); class DataLogic { //function to obtain Employee names from RealID array to pass to MSSQL for call count function GetEmpNames ($RealID) { global $ems_db_connect; foreach ($RealID as $emplist){ $query1 = mysql_query ("SELECT FirstName, LastName FROM ems_employee_list WHERE RealID=$emplist", $ems_db_connect) or die(mysql_error());; while($row = mysql_fetch_array($query1)) { $FirstName[] = $row['FirstName']; $LastName[] = $row['LastName']; } } $friendlyname = array('first_name' => $FirstName, 'last_name' =>$LastName); return $friendlyname; } //function to display Employee names from RealID array obtained from department and shift function DisplayEmpNames ($RealID) { global $ems_db_connect; foreach ($RealID as $emplist){ $query1 = mysql_query ("SELECT FirstName, LastName FROM ems_employee_list WHERE RealID=$emplist", $ems_db_connect) or die(mysql_error());; while($row = mysql_fetch_array($query1)) { $FirstName = $row['FirstName']; $LastName = $row['LastName']; $fullname[] = "$LastName, $FirstName"; } } return $fullname; } //function to pull the RealID's of Employees based on shift //Returns a list of RealID's for use with GetIris and RepSort functions function SelectEmpShift ($key) { global $ems_db_connect; switch($key) { case "First": $shift = 1; break; case "Second": $shift = 2; break; case "Third": $shift = 3; break; default: $shift = 4; } if ($shift == 4){ $query1 = mysql_query ("SELECT RealID FROM ems_employee_list LEFT JOIN ems_employee_schedules USING (EmployeeID) WHERE RealID > 0 AND Department='AHS'", $ems_db_connect) or die(mysql_error()); while ($row = mysql_fetch_array($query1)) { $x[]=$row['RealID']; } } else { $query1 = mysql_query ("SELECT RealID FROM ems_employee_list LEFT JOIN ems_employee_schedules USING (EmployeeID) WHERE RealID > 0 AND Shift = $shift AND Department ='AHS'", $ems_db_connect); while ($row = mysql_fetch_array($query1)) { $x[]=$row['RealID']; } } return $x; } //Function to Select Employees based on Department function SelectEmpDep ($key) { global $ems_db_connect; switch($key) { case "Managed Support": $deptcode = 6; break; case "Server Support": $deptcode = 5; break; case "Advanced Hosting Support": $deptcode = 2; break; default: $deptcode = 7; } if ($deptcode == 7){ $query1 = mysql_query ("SELECT RealID FROM ems_employee_list LEFT JOIN ems_employee_schedules USING (EmployeeID) WHERE RealID > 0 AND Department='AHS'", $ems_db_connect) or die(mysql_error()); while ($row = mysql_fetch_array($query1)) { $x[]=$row['RealID']; } } elseif ($deptcode == 5){ $query1 = mysql_query ("SELECT RealID FROM ems_employee_list LEFT JOIN ems_employee_schedules USING (EmployeeID) WHERE RealID > 0 AND AccessID=5 OR AccessID=3 AND Department='AHS' AND RealID >0", $ems_db_connect) or die(mysql_error()); while ($row = mysql_fetch_array($query1)) { $x[]=$row['RealID']; } } else { $query1 = mysql_query ("SELECT RealID FROM ems_employee_list LEFT JOIN ems_employee_schedules USING (EmployeeID) WHERE RealID > 0 AND AccessID=$deptcode AND Department ='AHS' ", $ems_db_connect); while ($row = mysql_fetch_array($query1)) { $x[]=$row['RealID']; } } return $x; } //function to sort Shift by multiple Deparments function RepSortShiftDept ($RealIDShift, $RealIDDepartment='', $RealIDDepartment2='') { $deptnumber = func_num_args(); if ($deptnumber == 1) { $result = $RealIDShift; } elseif ($deptnumber == 2) { $result = array_intersect($RealIDShift, $RealIDDepartment); } else { $result = array_intersect($RealIDShift, array_merge($RealIDDepartment, $RealIDDepartment2)); } return $result; } //function to sort Department by multiple Shifts function RepSortDeptShift ($RealIDDepartment, $RealIDShift='', $RealIDShift2='') { $shiftnumber = func_num_args(); if ($shiftnumber == 1) { $result = $RealIDDepartment; } elseif ($shiftnumber == 2) { $result = array_intersect($RealIDDepartment, $RealIDShift); } else { $result = array_intersect($RealIDDepartment, array_merge($RealIDShift, $RealIDShift2)); } return $result; } //Function to get and display count of Iris tickets from a date rage. //$RealID needs to be an array of EmployeeIDs obtained from SelectEmpShift, SelectEmpDepart, and RepSort functions function GetIris($RealID, $startdate, $enddate) { global $hocstat_db_connect; foreach ($RealID as $emplist){ $mssqlquery = "SELECT COUNT (IncidentID) AS mycount FROM hocstats.dbo.DailyStatsEmployee WHERE hocstats.dbo.DailyStatsEmployee.EmployeeID=$emplist AND(hocstats.dbo.DailyStatsEmployee.DateModified BETWEEN '$startdate 00:00:00.000' AND '$enddate 23:59:59.000')"; $query_3 = mssql_query ($mssqlquery, $hocstat_db_connect); $row =(mssql_fetch_array($query_3)) ; $iriscount[] = $row['mycount']; } return $iriscount; } //Function to get and display call counts from a date range. For use with GetEmpName ONLY function GetCalls ($friendlyname, $startdate, $enddate) { global $hocstat_db_connect; for ($x = 0; $x < count ($friendlyname['last_name']); $x++) { $query1 ="SELECT ISNULL(SUM(CallsHandledToHalf), 0) AS calls FROM Agent_Skill_Group_Half_Hour ASGHH WITH (NOLOCK) INNER JOIN dbo.agent ON ASGHH.skilltargetid = dbo.agent.skilltargetid WHERE(dbo.agent.enterprisename = 'HOC_{$friendlyname['last_name'][$x]}_{$friendlyname['first_name'][$x]}' OR dbo.agent.enterprisename = '{$friendlyname['last_name'][$x]}_{$friendlyname['first_name'][$x]}') AND (ASGHH.datetime BETWEEN '$startdate 00:00:00' AND '$enddate 23:59:00')"; $mssqlquery = mssql_query ($query1, $hocstat_db_connect); while ($row =(mssql_fetch_array($mssqlquery))) { $callcount[] = $row['calls']; } } return $callcount; } }//class close if($_POST) //setting varibles from form input { $shift_id= isset($_POST['shift']) ? trim($_POST['shift']) : die('Missing entry: Shift Selection'); $start_date= isset($_POST['startdate']) ? trim($_POST['startdate']) : die('Missing enty: Start Date'); $end_date= isset($_POST['enddate']) ? trim($_POST['enddate']) : die('Missing enty: End Date'); $depart_id= isset($_POST['department']) ? trim($_POST['department']) : die('Missing entry: Shift Selection'); } echo "You have selected stats for $shift_id shift(s) and $depart_id department(s) from $start_date to $end_date. </br>" ; $test=new DataLogic(); $calls = $test->GetCalls($test->GetEmpNames($test->RepSortShiftDept($test->SelectEmpShift("$shift_id"), $test->SelectEmpDep("$depart_id"))), $start_date, $end_date); $iris= $test->GetIris ($test->RepSortShiftDept($test->SelectEmpShift("$shift_id"), $test->SelectEmpDep("$depart_id")), $start_date, $end_date); $name= $test-> DisplayEmpNames($test->RepSortShiftDept($test->SelectEmpShift("$shift_id"), $test->SelectEmpDep("$depart_id"))); $table = array ( 'calls' => $calls, 'iris' => $iris, 'name' => $name); for ($x = 0; $x < count ($table['calls']); $x++) { echo $table["name"][$x]; echo "</br> Calls Taken :"; echo $table["calls"][$x]; echo "</br> Iris Tickets Resolved:"; echo $table["iris"][$x]; echo "</br>"; } ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=359434.0 Logic problem: Current directory listing at: http://www.nmlta.org...member_list.php shows the format I need. The only way I have previously been able to accomplish that format is by running four separate queries in a loop, which I understand is not good. Trying to simplify this, I need to explain my data. There are companies, and contact people at those companies, and some companies have branches, and most branches have contact people at them.
There are four tables: company, co_contact, branch, br_contact. The company, co_contact and branch tables all have a field called “company_id” to match the ones that go together, and the branch table also has a “branch_id” field to match with the people in the br_contact table.
I am successful with running separate JOIN queries for company/co_contact matching on “company_id”, and for branch/br_contact matching on “branch_id”, and have successful processes for listing the data properly.
My problem is I can’t find the logic to run them all in one query or loop that will produce the desired output I’m getting with my current four-query mess. The process should go like this:
List company1 info
List all contacts at company1
List branch1 connected to company1 (if applicable)
List all contacts at branch1 of company1
List branch2 connected to company1 (if applicable)
List all contacts at branch2 of company1
Etc. until all branches are listed for company1
Start over with company2…
Here is the code for my first attempt:
<?php function listCompany($row) { echo $row['comp_name'],"<br />"; if (!empty($row['comp_uw'])) { echo $row['comp_uw'],"<br />";} echo "</b>",$row['comp_street'],"<br />"; if (!empty($row['comp_pobox'])) { echo $row['comp_pobox'],"<br />";} echo $row['comp_csz'],"<br />"; echo $row['comp_ph'],"   Fax: ",$row['comp_fx'],"<br />"; if (!empty($row['comp_tfree'])) { echo "Toll Free: ",$row['comp_tfree'],"<br />";} if (!empty($row['comp_email'])) { echo "Email: <a href='mailto:",$row['comp_email'],"'>",$row['comp_email'],"</a><br />";} if (!empty($row['comp_web'])) { echo "<a href='http://",$row['comp_web'],"' target='_blank'>",$row['comp_web'],"</a><br />";} echo "</p>"; } function listBranch($row2) { if (!empty($row2['br_name'])) { echo "<p>     <b>",$row2['br_name'],"</b><br />";} echo "     ",$row2['br_street'],"<br />"; echo "     ",$row2['br_csz'],"<br />"; echo "     ",$row2['br_ph'],"   ",$row2['br_fx'],"<br /></p>"; } function listContact($row) { if (!empty($row['cont_name'])) { echo "<p>     <b>",$row['cont_name'],"</b>, ",$row['cont_title'],"<br />";} if (!empty($row['cont_email'])) { echo "     Email: <a href='mailto:",$row['cont_email'],"'>",$row['cont_email'],"</a><br />";} echo "</p>"; } function listBranchContact($row2) { if (!empty($row2['cont_name'])) { echo "<p>          <b>",$row2['cont_name'],"</b>, ",$row2['cont_title'],"<br />";} if (!empty($row2['cont_email'])) { echo "          Email: <a href='mailto:",$row2['cont_email'],"'>",$row2['cont_email'],"</a><br />";} echo "</p>"; } // Connection to DB $mysqli = new mysqli("localhost", "nmlta_admin", "trooper", "nmlta_agents"); if($mysqli->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } // Retrieve all the data from the "company" table for County and join matching people from the "co_contact" table $query = "SELECT * FROM company LEFT JOIN co_contact ON company.company_id = co_contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, co_contact.cont_rank"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); // Initialize variable $lastCompany = ''; // Start building the table to show results echo "<table border='1' cellpadding='10' cellspacing='0' bgcolor='#f0f0f0' style='margin-left:100px; margin-bottom:20px'>"; // Begin the Company "while" loop for rows in the $result while($row = $result->fetch_assoc()) { // Company - Loop 1 // Check if this is a different company than the last one if ($lastCompany != $row['company_id']) { // New Company Check - Loop 2 // If this is a different company - change the $lastCompany variable $lastCompany = $row['company_id']; echo "<tr><td><p><b>"; // List the company info only if it is not the $lastCompany listCompany($row); } // End New Company Check - Loop 2 // List all Contacts in the Company listContact($row); if ($row[next($row['company_id'] != $lastCompany)]) { // Start Branch // Retrieve all the data from the "branch" table for County and join matching people from the "br_contact" table $query2 = "SELECT * FROM branch LEFT JOIN br_contact ON branch.branch_id = br_contact.branch_id WHERE company_id = '".$row['company_id']."' ORDER BY branch.comp_name, branch.br_street, br_contact.cont_rank"; $result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__); // Initialize variable $lastBranch = 'xxx'; //Initialize $lastBranch variable // Begin the Branch "while" loop for rows in the $result2 while($row2 = $result2->fetch_assoc()) { // Branch - Loop 1 // Check if this is a different branch than the last one if ($lastBranch != $row2['branch_id']) { // New Branch Check - Loop 2 // If this is a different branch - change the $lastBranch variable $lastBranch = $row2['branch_id']; echo "<tr><td>"; // List the branch info only if it is not the $lastBranch listBranch($row2); } // End New Branch Check - Loop 2 // List all Contacts in the Branch listBranchContact($row2); } // End Branch - Loop 1 } } // End Company - Loop 1 echo "</td></tr>"; // Free result set mysqli_free_result($result); echo "</table>"; mysqli_close($mysqli); ?>My first thought was to insert the "if ($row[next($row['company_id'] != $lastCompany)]) {" qualifier after listing the contact for the company being processed, that way when I know a new company is on the next row, I can pause and run my second query to find any applicable branches that match the current company_id. The syntax must be wrong the way I have it, because I get an error with this, saying: "Fatal error: Only variables can be passed by reference in..." referencing that call in my code. I don't know if there is a syntax change that would make this work, or not. I have thought about, and tried different ways to run a query using JOIN on all four of my tables, but the resulting rows do not correspond with the order in which I need to process them, if that makes sense. I am not opposed to any suggestions that will make this work - I just can't seem to think it through and find the correct solution, if there is one. The difficulty seems to me to be that the process of listing company/contact info needs to know when it has reached the last row containing a contact tied to the company, so that the branch routine can be processed for the same company. Any help or suggestions would be appreciated. Thanks! i have two multi-dimensional arrays that i'd like to manipulate to check a few things. Their structures are different and i'm giving myself headaches trying to think through this. I have a $sums array which has information on a product in a purchase order. The second array consists of items(products) that are going to update the purchase order. So the first array key of $sums correlates with the "order" of the $items array. I'd like to write a function that: 1. Makes sure the first array key of $sums exists as an "order" value in the $items array. 2. Makes sure the $items price is greater than the $sums price Code: [Select] <?php $sums['23']['collected']['price'] = 30; $sums['73']['collected']['price'] = 60; $sums['89']['collected']['price'] = 90; $items['abc123']['order'] = '23'; $items['abc123']['price'] = 14; $items['321cba']['order'] = '73'; $items['321cba']['price'] = 79; function check_items($sums,$items) { $error = ""; //Makes sure the first array key of $sums exists as "order" value in the $items array. //If not -> $error = "Item #".$key." is not found in the items array."; //where $key is either the first array key of $sums or the "order" value in $items because they are the same thing //if found in $sums if($items[$hash]['price'] < $sums[$items[$hash]['collected']['price'] ) { $error = "Item #".$items[$hash]['order']."'s price must not be lower than ".$sums[$items[$hash]['order']]['collected']['price']; } return $error; } // $sums['23'] would cause an error because its price of 14 is less than 30 // $sums['73'] would pass because it exists in $items and its price of 79 is greater than the $sums price of 60. // $sums['89'] would cause an error because there is no $item corresponding to it ?> I just don't know where to put the foreach loops or where to even start really :/ I have a file sharing script, where each file has a certain number of points. I need to subtract a set number of points from the total. I'm unsure about the logic of it. This is how I total the number of points: Code: [Select] <?php $fq = "SELECT * FROM `files` WHERE owner='$username' AND active=1"; $fw = $sql->query($fq); $reward = 0; while($fr = $fw->fetch_assoc()){ $reward = $fr['points'] + $reward; }?> I'm thinking I should use a loop, while a the number to subtract is greater than or equal than 0. Can anyone help? I want to ask the user questions by using a form. I have a text field where the user inputs either 1 or 2 and then they press submit. I can get this to work but I need to keep asking them questions based off there last answer to the previus question.
I am making a game where you start with a number ex 5 and then you either choose to take away 1 or two from that number. so we take away 2 now the number is 3 and then the computer has his go using the same number. He chooses to take away 1 which makes the number 2. Now we take away 2 and win the game for being the first one to get the number down to 0. Its a very simple game that im trying to do just to brush up on my php skills.
my code so far....
<p> please enter a number to begin the subtraction game</p> <form name="submit1" method="post"> <input type="text" name="startingNumber"> <input type="submit" name='submit1'> </form> <?php if (!empty($_POST['startingNumber'])) {?> <p>your starting number is: <?php echo $_POST['startingNumber']?></p> <?php while(!$_POST['startingNumber'] == 0){?> <p> Would you like to minus one or two from <?php echo $_POST['startingNumber']; ?></p> <form name="submit2" method="post"> <input type="text" name="oneOrTwo"> <input type="submit" name='submit2'> </form> <?php } }?>As you can see i am no where near close to getting this right. Im thinking i have to use a while loop to keep asking the question minus 1 or 2 until they reach 0. Inside this while loop im thinking i need something like a waituntil user has clicked submit. In fact i have written the same game in c++ so if it helps here is that. (it works just how i want it too) the problem im having is that in c++ you can use cin to get a input from the user and it waits until the user types in a value but im struggling to find anything like that in php. Any help would be greatly appreciated thank you. #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int number, oneOrTwo, remainder; cout << "please enter a number to begin the subtraction game"; cin >> number; while (number != 0){ cout <<"your turn, subtract 1 or 2 from " << number << endl; cin >> oneOrTwo; if (oneOrTwo == 1 || oneOrTwo == 2){ number = number - oneOrTwo; }else{ cout << "sorry you have entered a incorrect number. Please enter either 1 or 2" << endl; continue; } if (number == 0){ cout << "congratulations! you won the game"; break; } remainder = number % 3; if (remainder % 3 == 0){ remainder = 2; } cout << "now my turn im going to subtract " << remainder << " from " << number << endl; number = number - remainder; if (number == 0){ cout << "sorry the computer won this time"; } } system("PAUSE"); return EXIT_SUCCESS; } Edited by yacobm8, 16 May 2014 - 12:14 AM. Hi all, Its been a while since I looked at PHP and I have forgotten some basics What I am trying to achieve is display category names, sub categories and results into a list Code: [Select] <ul id="nav"> <li><a href="#">Main Cat</a> <ul> <li><a href="#">Sub Cat 1</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </li> <li><a href="#">Sub Cat 2</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </ul> </li> What would be the best way to organise my database? Have everything in one entry like: main_id / sub_id / listing_id / listing_name or separate them into a table for cats, one for sub cats and what parent it belongs to, then a table for the listings linking to the sub cat it belongs to? I have confused myself no end on how then to display the results, so any help with would be gratefully received! Thanks Dave I am trying to understand PHP While Loops. For example. $info=mysql_fetch_array($query); will create an array of a mysql query. how does while($info=mysql_fetch_array($query) { echo $info['1']; } ensure that each element of the array is echoed. It seems that $info is a one time statement that grabs an array, how does adding While make it capable of being extended into rows? To me this says While this is true, do this. But if it is true once, how does PHP know when to stop? i have an array called $imageArray like this Array ( [0] => 'Dashka'_Darren_Sheehan_1.jpg [1] => 'Dashka'_Darren_Sheehan_10.jpg [2] => 'Dashka'_Darren_Sheehan_2.jpg [3] => 'Dashka'_Darren_Sheehan_3.jpg [4] => 'Dashka'_Darren_Sheehan_4.jpg [5] => 'Dashka'_Darren_Sheehan_5.jpg [6] => 'Dashka'_Darren_Sheehan_6.jpg [7] => 'Dashka'_Darren_Sheehan_7.jpg [8] => 'Dashka'_Darren_Sheehan_8.jpg [9] => 'Dashka'_Darren_Sheehan_9.jpg [10] => . [11] => .. [12] => Aaron_Kidney_1.jpg [13] => Aaron_Kidney_10.jpg [14] => Aaron_Kidney_11.jpg [15] => Aaron_Kidney_12.jpg [16] => Aaron_Kidney_13.jpg [17] => Aaron_Kidney_14.jpg [18] => Aaron_Kidney_15.jpg [19] => Aaron_Kidney_16.jpg [20] => Aaron_Kidney_17.jpg [21] => Aaron_Kidney_18.jpg and i also have another array called $_names Array ( [0] => 'Dashka'_Darren_Sheehan [1] => Beefit_Gyms [2] => Aaron_Kidney [3] => Dean_Mitchell [4] => Colin_O_Neill [5] => Keith_McManus ) if a name in array $_names exists in the $imageArray i want to insert the images for that person into one column of a table like this <tr> <?php foreach ($names as $name): ?><th><?php htmlout($name); ?></th><?php endforeach; ?> </tr> <tr> <td><img src="../images/'Dashka'_Darren_Sheehan_1.jpg" width="204"/></td> <td><img src="../images/Aaron_Kidney_1.jpg" width="204"/></td> <td>row 1, cell 1</td> <td>row 1, cell 2</td> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td><img src="../images/'Dashka'_Darren_Sheehan_2.jpg" width="204"/></td> <td><img src="../images/Aaron_Kidney_2.jpg" width="204"/></td> <td>row 1, cell 1</td> <td>row 1, cell 2</td> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> can anyone help me write the logic for this?? I cant figure it out... So I have this killer script I wrote for article management across multiple sites. I am trying to make a drip feed so you can set up a bunch of articles for one site to drip out over x amount of days. Then you could do that for your next site etc... so you do not need to manage all of your 20 blogs/sites a day. So, I am thinking I have all these variables in a table: Code: [Select] Table 1 Article - URL for article - Title - Keywords - Anchor Text - URL link - Category - Site to post to ID Code: [Select] Table 2... URL - Date Posted - Drip Feed (maybe include category here because in table 1 it will repeat category for every row of the same url) Then I make a script that runs on a cron job every 2-4 hrs... Not sure the best way to make the script and also not sure the best way to post this info to different sites... ideally id like to be able to post to joomla, wordpress, blogspots, etc... basically many different kinds of sites. Any suggestions would be appreciated... no need for you to write the code I can do that, just need a plan. I make a query where I fetch som individuals and group them by class and count the rows. I make a for statement and in that statement I make a new query where I fetch all individuals in each class and sort them by id. Each member in each class should be printed into a file, limited by 15, if there is more than 15 the rest should be printed to the next file. My logic is a little confusing to me... Code: [Select] $queryorder = "SELECT * FROM mytable GROUP BY class ORDER BY cat_order"; count $rows1... for ($ii = 0; $ii < $rows1; $ii++) { $query = "SELECT * FROM mytable WHERE class = '". $rows1[$ii]['class'] . "' ORDER BY id"; $rows2 $count = 1; $sid_nr = 1; $list_nr = 1; for ($iii = 0; $iii < $rows2; $iii++) { if($count == 1) { createnewfile $ring = $rows2[$iii]['ring']; } for($count_i = 1; $count_i < 16; $count_i++): if($rows2[$iii]['C'] == 1){$rows2[$iii]['C'] = 'C';}else{$rows2[$iii]['C'] = '';} if($rows2[$iii]['S'] == 1){$rows2[$iii]['S'] = 'S';}else{$rows2[$iii]['S'] = '';} if($count_i == $count) { variabel1='VAR1'.$count_i, $rows2[$iii]['nr']); variabel2='CS'.$count_i, $rows2[$iii]['C'] . $rows2[$iii]['S']); variabel3='NAME'.$count_i, $rows2[$iii]['id_nr'] . ' ' . $rows2[$iii]['name']); } endfor; $count++; if($count == 15) { $filename = somefilename; $myFile = $resultiddir.DS.$filename; closefile $count = 1; $sid_nr++; } if($count == $rows2 { $filename = somefilename; $myFile = $resultiddir.DS.$filename; closefile $count = 1; $sid_nr = 1; } } } Some of it is pseudocode but the idea is the important thing:) Hey guys, I have a question that you can hopefully help me with, I'm writing a simple forum, and I'm wondering how I would go by handling a thread that has been 'stuck' so that it isn't moved when more threads are made. I could use some a push in the right direction thanks. Hey All,
I'm creating a function in javascript and I'm having a bit of trouble trying to figure out the logic.
Here is the breakdown. I have a json database that will output some text into the main index.html file. This text is broken up into different entries each tagged with different categories. On the index.html the user clicks on the categories they want and then click on either one of two buttons.
The first button will show the text items that have any of the categories, so if they select categories 1 and 3, the function will show any of the text items with those categories. (This part works)
The second button i want to show text that only have all the selected categories. So if they selected category one and three, then only items with one AND three will show It could have other categories tagged, but it has to have the selected tags in the same item. I'm just trying to figure out how to isolate just those items.
Here is the code for the first button. I'm not a solid coder and most of this has been trial and error after error. I just need to figure out something similar for the second button.
function loadInfoOr() { $.getJSON('data.json', function(data) { var output = '<ul class="searchresults">'; $.each(data, function(key, val) { if ((val.env.search(env) != -1) || (val.pri.search(pri) != -1) || (val.per.search(per) != -1) || (val.ind.search(ind) != -1) || (val.com.search(com) != -1) || (val.res.search(res) != -1) || (val.myr.search(myr) != -1) || (val.saf.search(saf) != -1) || (val.ewa.search(ewa) != -1)) { output += '<li class="itemWrapper">'; output += '<h2>'+ val.Header; if ((val.env.search("ENV") != -1)) { output += '<span class="tag env">ENV</span>'; } if ((val.pri.search("PRI") != -1)) { output += '<span class="tag pri">PRI</span>'; } if ((val.per.search("PER") != -1)) { output += '<span class="tag per">PER</span>'; } if ((val.com.search("COM") != -1)) { output += '<span class="tag ind">IND</span>'; } if ((val.ind.search("IND") != -1)) { output += '<span class="tag com">COM</span>'; } if ((val.res.search("RES") != -1)) { output += '<span class="tag res">RES</span>'; } if ((val.saf.search("MYR") != -1)) { output += '<span class="tag myr">MYR</span>'; } if ((val.myr.search("SAF") != -1)) { output += '<span class="tag saf">SAF</span>'; } if ((val.ewa.search("EWA") != -1)) { output += '<span class="tag ewa">EWA</span>'; } output += '</h2>'; output += '<p>'+ val.statement +'</p>'; output += '</li>'; } }); output += '</ul>'; $('#textArea').html(output); }); }; Hi All, I'm trying to understand the logic behind this bit of code I found. I (think I) get that it takes an argument which in this case is a number, an checks to see if the array isset, then uses a while loop to loop through the possible values taking each value and placing it into another function which performs some task. What I'm really confused about is how the code is using unset, If I'm correct it's unsetting the incremented value which is the value that should be used in the next iteration, now I know this is not the case, but I don't understand why this is working. I have included the code in the topic and I also wrote a small piece of code to mirror this so I could play around with it in hopes of understanding the logic but it gives me a syntax error in my IDE when I try to unset the incremented value. I know this is probably something really stupid so be kind. <?php define("NUM_0", 0); define("NUM_1", 1); define("NUM_2", 2); define("NUM_3", 3); define("NUM_4", 4); function function_1($position) { static $positions = array(NUM_0, NUM_1, NUM_2, NUM_3, NUM_4,), $index = 0; if (isset($positions[$index])) { while ($position >= $index) { $current_position = $positions[$index]; unset($positions[$index++]); function_2($current_position); } } } function function_2($position) { switch ($position) { case 0: echo '$position equals 0 <br />'; break; case 1: echo '$position equals 1 <br />'; break; case 2: echo '$position equals 2 <br />'; break; case 3: echo '$position equals 3 <br />'; break; case 4: echo '$position equals 4 <br />'; break; } } function_1(NUM_4); [b] [u]output![/u] $position equals 0 $position equals 1 $position equals 2 $position equals 3 $position equals 4 [/b] function test() { static $var_1; $var_1 = 10; if (isset($var_1)) { while ($var_1 >= 0) { $var_2 = $var_1; unset ($var_1++); // syntax error on this line. echo $var_2; } } } test(); ?> write the algorithm to draw a sphere, the function should have parameters 1. diameter (how many line) 2. character (use which character to draw) eg, draw_sphere(10, '8') will produce: 88888 8888888888888 8888888888888888888 888888888888888888888 88888888888888888888888 88888888888888888888888 888888888888888888888 8888888888888888888 8888888888888 88888 the above is a sphere of 10 lines, which is drawn using the character "8" i cant figure out how to do it, thanks in advanved! I'm just trying to see if the order of my logic is correct or if there's something I can do differently. I'm also curious to know at what point I should get the 2 passwords that exists in the database for the user. These are two different passwords. Code: [Select] function login_submit() { $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); $this->form_validation->set_rules('remember', 'Remember me', 'integer'); $user_id = $this->users->get_user_id_by_username($this->input->post('username')); if ($user_id !== 0) { if ($this->kow_auth->is_max_login_attempts_exceeded($user_id)) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again!')); } else { $user_status = $this->users->get_user_status($user_id); if ($user_status == 1) { echo json_encode(array('error' => 'yes', 'message' => 'Sorry you must verify your account before logging in!')); } elseif ($user_status == 3) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been suspended!')); } elseif ($user_status == 4) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently banned!')); } elseif ($user_status == 5) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been deleted!')); } else { if ($this->form_validation->run()) { if ($this->kow_auth->login($this->form_validation->set_value('username'), $this->form_validation->set_value('password'), $this->form_validation->set_value('remember'))) { redirect(''); } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } } } } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } Okay, so I'm pretty new to jQuery but I am pretty experienced with PHP. I am about to begin coding a script written mostly in jQuery. It will use AJAX to verify that an article tag a user provides exists in a database. When a user goes to write an article on my website, my form will ask them to add keyword tags which will be used in searches. Basically only admins will be allowed to create new tags, so this is why I check the tags first. And also to prevent duplicates and similar tag entries in the database.
The form will have a single input that the user will use to search for a tag. Once the user hits the enter key, it will search the database for tags that already exist. Once the ajax is complete, a list of related tags will pop up and the user will be able to select their desired tag by either clicking the tag link in the list or by pressing enter.
This is a very crude demonstration of what my idea is.
Hi Guys, I'm sure my logic is off somewhere in my code, basicaly i resize an uploaded image and move to it's location depending on whether it came from the US or UK site: Resize Function: function resize_image($uploadDirectory, $newFileName, $us = false) { $original_image = $uploadDirectory; $ext = substr($original_image, strrpos($original_image, '.') + 1); $canvas_width = 65; $canvas_height = 65; $canvas = imagecreatetruecolor($canvas_width, $canvas_height); $white_background = imagecolorallocate($canvas, 255, 255, 255); imagefill($canvas, 0, 0, $white_background); list($image_width, $image_height) = getimagesize($uploadDirectory); $ratio = $image_width / $image_height; if ($ratio > 1) { $new_image_width = 65; $new_image_height = 65 / $ratio; } //$ratio > 1 else { $new_image_width = (float) 65 * $ratio; $new_image_height = 65; } if ($ext == "jpg") { $original_image = imagecreatefromjpeg($original_image); } //$ext == "jpg" if ($ext == "gif") { $original_image = imagecreatefromgif($original_image); } //$ext == "gif" imagecopyresampled($canvas, $original_image, 0, 0, 0, 0, $new_image_width, $new_image_height, $image_width, $image_height); $new_thumbnail_name = "thumb-$newFileName"; if ($ext == "jpg") { if ($us) { imagejpeg($canvas, "../../site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagejpeg($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "jpg" if ($ext == "gif") { if ($us) { imagegif($canvas, "../../first-site.com/imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } else { imagegif($canvas, "../imgProducts/img-th/$new_thumbnail_name", 100); return ("$new_thumbnail_name"); } } //$ext == "gif" imagedestroy($original_image); imagedestroy($canvas); } Upload Code: <?php if (isset($_POST['submit-add-product'])) { $productNM = ucwords($_POST['txt-product-name']); $productDS = escape_data($_POST['txt-product-description'], 1); $productPM = $_POST['txt-product-p-medicine']; $productCT = $_POST['txt-product-category']; $productPR = $_POST['txt-product-price']; $productST = $_POST['txtSite']; $fileName = $_FILES['txt-product-image']['name']; $fileTemp = $_FILES['txt-product-image']['tmp_name']; $fileType = $_FILES['txt-product-image']['type']; $fileSize = $_FILES['txt-product-image']['size']; /*if (!empty($_FILES['txt-product-image-2']['name'])) { $fileName2nd = $_FILES['txt-product-image-2']['name']; $fileTemp2nd = $_FILES['txt-product-image-2']['tmp_name']; $fileType2nd = $_FILES['txt-product-image-2']['type']; $fileSize2nd = $_FILES['txt-product-image-2']['size']; $fileExtension = substr(strrchr($fileName2nd, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName2nd = str_replace(" ", "-", $productNM . "-2nd"); $newFileName2nd = "$replacedName2nd-" . time() . "$fileExtension"; $uploadDirectory2nd = "../imgProducts/img-fs/$newFileName2nd"; $generate2ndImage = true; } //!empty($_FILES['txt-product-image-2']['name']) if (empty($productNM)) { print "<p class=\"fcp-message-error\">You never entered a product name.</p>"; } //empty($productNM) if (empty($productDS)) { print "<p class=\"fcp-message-error\">You never entered a product description.</p>"; } //empty($productDS) if (empty($productPR)) { print "<p class=\"fcp-message-error\">You never entered a product price.</p>"; } //empty($productPR) if (empty($fileSize)) { print "<p class=\"fcp-message-error\">You never entered a product image.</p>"; } //empty($fileSize) if (!isImageFile($fileType)) { print "<p class=\"fcp-message-error\">The file you uploaded doesn't seem to be an image.</p>"; } //!isImageFile($fileType)*/ $fileExtension = substr(strrchr($fileName, '.'), 0); $fileExtension = strtolower($fileExtension); $replacedName = str_replace(" ", "-", $productNM); $newFileName = "$replacedName-" . time() . "$fileExtension"; $uploadDirectory = "../imgProducts/img-fs/$newFileName"; // US // if ($productST == "US") { $uploadDirectory = "../../first-choice-pharmacy.com/imgProducts/img-fs/$newFileName"; //move_uploaded_file($fileTemp, $uploadDirectory2nd); if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName, 1); $productTH = resize_image($uploadDirectory, $newFileName, 1); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','US',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = ''; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } elseif($productST == "UK") { if (move_uploaded_file($fileTemp, $uploadDirectory)) { $productWM = watermark_image($uploadDirectory, $newFileName); $productTH = resize_image($uploadDirectory, $newFileName); } //move_uploaded_file($fileTemp, $uploadDirectory) /*if (isset($generate2ndImage)) { watermark_image($uploadDirectory2nd, $fileTemp2nd); move_uploaded_file($fileTemp2nd, $uploadDirectory2nd); } //isset($generate2ndImage)*/ $qI = mysql_query("INSERT INTO `fcpv3_products` (`id`,`category_id`,`product_name`,`product_description`,`product_thumbnail`,`product_fullsize`,`product_fullsize_second`,`product_price`,`product_weight`,`p_med`,`is_breakable`,`site`,`date_added`) VALUES ('','$productCT','$productNM','$productDS','$productTH','$newFileName','$newFileName2nd','$productPR','0.00','$productPM','N','UK',NOW())"); if ($_POST['updateTwitter'] == "yes") { $last_product_id = mysql_insert_id(); $twitter_url = generate_seo_friendly_links($productNM, $last_product_id); $username = 'firstchoicephar'; $password = 'milr'; $status = urlencode(stripslashes(urldecode('We just added ' . $productNM . ' http://www.firstchoicepharmacy.co.uk/product.php?id=' . mysql_insert_id()))); if ($status) { $tweetUrl = 'http://www.twitter.com/statuses/update.xml'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "$tweetUrl"); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status"); curl_setopt($curl, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($curl); $resultArray = curl_getinfo($curl); if ($resultArray['http_code'] == 200) { print "<p class=\"fcp-message-success\">Tweet made successfully :).</p>"; } //$resultArray['http_code'] == 200 else { print '<p class="fcp-message-error">OOPS, an error has occured Posting to twitter, please contact the site administrator.</p>'; curl_close($curl); } } //$status if ($qI) { print "<p class=\"fcp-message-success\">You have successfully added a new product.</p>"; } //$qI else { print '<p class="fcp-message-error">OOPS, an error has occured please contact the site administrator.</p>'; } } //$_POST['updateTwitter'] == "yes" } } //isset($_POST['submit-add-product']) ?> When i change the $us flag the US site works and the UK one doesn't, the full size image always gets uploaded fine it appears to be my logic in the resize function (i think ) a fresh pair of eyes would be great thanks guys Graham Hey guys, I am not really asking for pure php code, as I know alot of if's and switches could do this, but I am thinking of a easier method, of using for each or something to make it alot more better (performance wise) here it goes. I have 70 images, 1.png to 70.png, they are STARS. People on my forum software can upgrade there account via paypal to become a "Site Donor" I use the paypal's IPN to update the "amount" field value in mysql for each member. So if a user donates 10$, and then he donates 10$ tomorrow, the "amount" field will have a total of "20$" in it. Now I need to show a page where it list's all 1-70.png STARS, and it will have a radio button next to each star for them to select (Based on the amount they donate) So if a person has only dated 5$ dollars, they will have access to starts 1 through 10.png. If a person donated 20$ they will have access to 1-20.png Stars to chose from, (and so on) What would be the easiest way to check the input so people can't tamper with my form value to get a let's say 50.png star when they only donated like 10 dollars? Should I use just a simple switch function with 70 Cases? Or is there a easier method? and how would I go about storing a value in a field when they make a payment so then I can just simply check that field with the users input so they can't tamper the data and try to get a higher star? |