Jump to content

Psycho

Moderators
  • Posts

    12,157
  • Joined

  • Last visited

  • Days Won

    129

Everything posted by Psycho

  1. As I stated, having record go from top down, then from left to right in columns is a little more difficult - but achievable. You state you want to do this from an array, but then you state this is from a database. It helps if you are clear on the source data - database. You can put the database results into an array, but it is not always necessary. So, try not to make assumptions that the data would have to be put into an array first. There are always multiple ways to do the same thing. Here is some sample code that should do what you need. <?php //Define number of columns $columns = 4; $query = "SELECT lastname, firstname FROM table_name ORDER BY lastname, firstname"; $results = $pdo->query($query); //Put results into an array $records = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC) { $records[] = $row; } //Calculate the number of rows per column $rows = ceil(count($records) / $columns); //Create Output for the rows of records $output = ""; for($row=0; $row<$rows; $row++) { $output .= "<tr>\n"; for($col=0; $col<$columns; $col++) { //Determine the index from the records array $idx = $row + ($col * $rows); //Prepare the content based on whether the index exists // - last row may not have records in all columns $content = isset({$records[$idx]) ? "{$records[$idx]['lastname']}, {$records[$idx]['firstname']}" : ''; $output .= " <td>{$content}<td>\n"; } $output .= "</tr>\n"; } ?> <table> <?php echo $output; ?> </table>
  2. If you are working with an array, you should almost always use foreach(). As ginerjm showed, a while() loop is typically used for scenarios like processing data from a query result - where you want the loop to continue until some specific condition occurs. As to the question about columns, I think I understand what you are trying to do. The implementation is pretty similar whether you are using an array or DB results. But, how do you want the data displayed in columns? Left to right going down OR top to bottom going to the right? The former is very easy and the latter is a little more difficult, but definitely achievable. Here is some sample code: <?php //Define number of columns $columns = 4; $query = "SELECT field1, field2 FROM table_name ORDER BY field1"; $results = $pdo->query($query); //Put results into an array $records = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC) { $records[] = $row; } //Split array into chunks based on column size $rows = array_chunk($records, $columns); //Create Output for the rows of records $output = ""; foreach($rows as $row) { $output .= "<tr>\n"; foreach($row as $record) { $output .= "<td>{$record['field1']}<br>{$record['field2']}<td>\n"; } $output .= "</tr>\n"; } ?> <table> <?php ech
  3. OK, my wording was not necessarily "precise". But the comment that it "would not work" was correct based upon his intended use And, although I don't think he specifically stated it, I inferred that the user would have multiple likes.
  4. There are other problems as well, such as this $username = htmlspecialchars($username); $username = htmlentities($username); $username = strip_tags($username); What is it you are trying too accomplish with this? htmlentities and htmlspecialchars do almost identical things. You would only need to use one or the other - but there's no reason to use either in this situation anyways. Plus, once either of those functions are run, strip_tags() would be useless. What prompted you to put all three of those like that? Then there's this if(preg_match("#[^\w]#", $username)) { die("Your username must be numbers or letters only!"); } This is a login script. You should state nothing about whether the username/password meets any specific criteria. That is only done where the user creates those values. This provides information to a potential malicious user regarding values they can exclude in their attempts to infiltrate your application. The code is a mess. As to the problem you asked about, the problem is how you structure it: if($row['rank'] == 1) { $_SESSION['loggedIn'] = 1; $_SESSION['username'] = $username; $_SESSION['rank'] = $row['rank']; echo '<meta http-equiv="refresh" content="0;admin.php">'; } $_SESSION['loggedIn'] = 1; $_SESSION['username'] = $username; $_SESSION['rank'] = $row['rank']; echo '<meta http-equiv="refresh" content="0;user.php">'; If the user is an admin, it echos <meta http-equiv="refresh" content="0;admin.php"> But, then it will also echo <meta http-equiv="refresh" content="0;user.php"> because you didn't put that second block within an else condition. So, there are TWO meta refresh tags created on the page for an admin.
  5. This line of code makes no sense: if (($username == $db_username) && (password_verify($db_password, $hash))) { The query should include the username in the WHERE clause. So only the record that matches the username would be returned (or no results would be returned). So, why would you need to verify the username from the DB results?
  6. The DB schema is incorrect and will not work. The user table should only hold things such as name, email, etc. Any "associations" (likes, groups, etc.) need to be stored in an associative table. That allows you to have no value, one value, or multiple values. The structure would look something like this: Users user_id, email Likes like_id, description Groups group_id, name, meet_dow (day of week, should be 1-7 since that is how MySQL understands Sun - Sat), meet_time, meet_length (:30 = 30 minutes) User_Likes (used to associate likes to users, one record for each user-like pair) user_id, like_id User_Groups (used to associate groups to users, one record for each user-group pair) user_id, group_id
  7. If you are determining the records to display for a quarter based on the order they exist in a table, then it is the wrong approach. There should be no need to keep data "tidy" for it to work. The data is the data - is the data. You should not need to manipulate the data in order to retrieve the results correctly. That just adds overhead. I should be able to add a new record to a table for the beginning of the year and my query to return the 1st quarter results will include it - even if it was added after or between records for April or May.
  8. @cyberRobot, that method is not recommended as it can still lead to duplicates due to race conditions. @saurav99990, There is a simple solution: ON DUPLICATE KEY UPDATE. You would need to set a UNIQUE constraint on the appropriate field - in your example it would be "CustomerName". Then you just create an INSERT query with an optional ON DUPLICATE condition. INSERT INTO Customers (CustomerName, ContactName, City) VALUES ('Alfreds Futterkiste', 'Alfred Schmidt', 'Hamburg') '<< Only provide data on this line ON DUPLICATE KEY UPDATE SET ContactName = VALUES(ContactName), SET City = VALUES(City) If a record with the CustomerName 'Alfreds Futterkiste' does not exist, a new record is created with the values for CustomerName, ContactName & City. If a record with that CustomerName does exist, then the fields for ContactName & City will be updated (if the values are different than what exists for the field currently)
  9. ???? public function import_ads() { //if(date("l")!='Thursday' && date("l")!='Friday') { //echo "test";die; $file_exists = FALSE; $i = 0; do { $date = date("m-d-y", time());
  10. Huh? I am not understanding you. What do you mean you only want one value? Are there multiple values per record (e.g. comma separated string) or are you saying you want the exact same value for every record?
  11. Never run queries in loops - it puts a lot of overhead on the server and, will eventually, result is significant performance issues. Also, if the user is selecting from predetermined values, you should not be using a LIKE condition. The options should be a lookup list using a unique if as a foreign key in the table you are searching. So, based on what you have provided, you should have another table such as 'makes' something like this: makes ================= id | make 1 BMW 2 Audi 3 Ford 4 Buick Then, in the 'Cars' table you would have a column for make_id using the numeric values above. You would not put 'BWM' as a value in the 'Cars' table, just the id. Then, you could dynamically create the checkboxes using the 'makes' table like so $query = "SELECT id, make FROM makes ORDER by make"; $result = mysqli_query($link, $query); $makeOptions = ''; while ($row = ) { $makeOptions .= "<input type='checkbox' name='makes[]' value='{$row['id']}'> {$row['make']}<br>\n"; } echo $makeOptions; Lastly, on the page that receives the form post, you would use those selected values to create a query using the IN operator //Get the passed make IDs $makeIDs = isset($_POST['makes']) ? $_POST['makes'] : array(); //Force to ints to prevent SQL injection $makeIDs = array_map('intval', $_POST['makes']); //Create variable for WHERE clause $WHERE = ""; //Used as if if no makes selected //If there are values, create an IN condition if($makeIDs) { $WHERE = " WHERE make_id IN (" . implode(',', $makeIDs) . ")"; } $query = "SELECT * FROM `Cars` {$WHERE}";
  12. What debugging code did you create and what were your results? I can't test your code as I don't have everything else that goes along with it. If you had implemented debugging lines like I provided above, you should have narrowed the problem down further. I'm not trying to be difficult, I'm trying to get you to learn. The find method has a flaw in that some 'values' can return false. Just run the query regardless of what is passed (assuming you are properly handling the data to protect against SQL Injection). Also, dynamically selecting which field to search is problematic. Are you preventing users from using a numeric value as their username? If not, the code would fail. public function find($user = null) { echo "DEBUG: the value '$user' was passed to find method.<br>\n"; $field = (is_numeric($user)) ? 'uid' : 'username'; echo "DEBUG: Search will be performed against the '$field' field.<br>\n"; $data = $this->_Database->get('users',array($field,'=',$user)); echo "DEBUG: Search returned " . $data->count() . " results.<br>\n"; if($data->count()) { $this->_data = $data->first(); return true; } return false; }
  13. Follow the same logic I provided above to the Login class to output debugging code. Check the true/false conditions as well as check the values of any important variables at key points.
  14. There are a lot of conditions in your code (i.e. if() statements), but not all of them have an else condition that would produce output. In other words, if some condition is not met you have nothing to let you know that it was not met. So, my guess is that one of those conditions is not being met and the logic you expect to run is not being executed. Add some debugging info so you can verify what is or is not happening. This isn't what you would want in "production" code, but should help find the problem. Although you should have error handling for all the conditions - just not as I added it below. $user = new User(); if(Input::exists()){ echo "DEBUG: Input does exist<br>\n"; if(Token::check(Input::get('token'))) { echo "DEBUG: Token check passed<br>\n"; try { $login = $user->login(Input::get('username'),Input::get('password')); if(!$login) { echo "DEBUG: Login error occured<br>\n"; Session::flash('login_error','Unable to login.'); } else { echo "DEBUG: Login error did not occur<br>\n"; Session::flash('logged_in','Logged In Success'); Redirect::to('home.php'); } } catch(Exception $e) { die($e->getMessage()); } } else { echo "DEBUG: Token check did not pass<br>\n"; } } else { echo "DEBUG: Input does not exist<br>\n"; }
  15. All web application that I have used which interact with a web camera (virtual meeting applications) all use plug-ins. Most of the ones have required a separate install, but one of the current ones we use appears to use Flash. You would either need to build your own plug-in or find a way to integrate with flash (I have no experience with this). So, not only can you not do this with PHP, you need something more than just HTML/JavaScript (probably). There could be something built into HTML5 to assist with this, but I doubt it. Seeing as it would interact with something on the user's PC it would definitely require user interaction to enable it. Could you imagine if some random web page was able to start your webcam and take pictures without your consent?
  16. 1. Don't use 'SELECT *' - state the fields you want in the SELECT clause. Using SELECT * can open you up to vulnerabilities and defects that you would not otherwise have. 2. If you only expect one record - don't use a loop to get the record. 3. There is no logic to handle a situation if the query fails 4. I would assume the 'id' is really dynamic and your example just doesn't show that. If so, you should be using prepared statements to prevent SQL injection 5. No need to create variables for the returned data - just use '$row['pos_x']', for example. It is a waste of code to create variables for ones that already exist. There are situations where you may need to do that, but this doesn't appear to be one. 1, Again, no code to check for errors. 2. I prefer to use named placeholders with bound parameters. That way you just assign a value to a variable and execute the query. 3. Also, by default, PDO only simulates prepared statements. You should turn emulation off to increase security $connect->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
  17. I second that. What you are doing seems to be overly complicated - there is more than likely a simpler solution It appears you are wanting only "approved" users to submit to this process. But, I see no reason for unique email addresses for users to send to. You already verify the sender of the email address, I would think that would suffice.
  18. FYI: You should never use pricing data passed from the client. Anyone can manipulate the data sent to your server. You should pass product IDs and quantities and then calculate on the back end only
  19. I just saw there was still some duplication, the "AND CURDATE() < t1.end_date" is duplicated between the OR conditions - so it can be simplified to WHERE t1.wearer_id = $order_wearer_id AND (CURDATE() >= t1.start_date OR CURDATE() >= t1.early_date) AND CURDATE() < t1.end_date AND ( ( overwrite_prevent_ordering <> 1 AND (t1.prevent_date IS NULL OR CURDATE() < t1.prevent_date) ) OR ( overwrite_prevent_ordering = 1 ) )
  20. The format of your WHERE clause appears to be more complicated than it needs to be. Also, FORMAT complicated logic so you can see the structure - it helps a lot. I made some modifications and put in the exception for when overwrite_prevent_ordering equals 1. SELECT t1.overwrite_prevent_ordering, t2.id, t2.title, t2.gender, t3.title AS employment_status, DATE_FORMAT(t1.start_date, '%Y-%m-%d') AS start_date, DATE_FORMAT(t1.end_date, '%Y-%m-%d') AS end_date, DATE_FORMAT(t1.early_date, '%Y-%m-%d') AS early_date, DATE_FORMAT(t1.prevent_date, '%Y-%m-%d') AS prevent_date FROM wearer_wardrobes t1 LEFT JOIN wardrobes t2 ON t1.wardrobe_id = t2.id LEFT JOIN employment_status_options t3 ON t2.employment_status = t3.id WHERE t1.wearer_id = $order_wearer_id AND (CURDATE() >= t1.start_date OR CURDATE() >= t1.early_date) AND ( ( overwrite_prevent_ordering <> 1 AND CURDATE() < t1.end_date AND (t1.prevent_date IS NULL OR CURDATE() < t1.prevent_date) ) OR ( overwrite_prevent_ordering = 1 AND CURDATE() < t1.end_date) ) )
  21. If you don't understand something that is provided - by all means ask! The main point of this site, in my opinion, is helping people learn. So, in that spirit, let me break down the query Barand provided (I defer to him on all things database!) using your field/table names: SELECT SUM(amount_paid) as qRes FROM history WHERE YEAR(last_payment) = YEAR(CURDATE()) AND QUARTER(last_payment) = :q The first line SELECT SUM(amount_paid) as qRes This add the total of all the 'amount_paid' fields of the records that will match the query FROM history We'll be selecting data from the history table WHERE YEAR(last_payment) = YEAR(CURDATE()) AND QUARTER(last_payment) = :q Ok, this is the real meat of the query. There are MySQL functions used: - YEAR() returns the year value of a date object - CURDATE() returns the current date [same as NOW(), but only the date portion] - QUARTER() returns the numerical quarter of a date object (i.e. 1, 2, 3 or 4). No need to defined Jan1 to Mar31 The WHERE clause will return all the records that match two conditions: 1. The YEAR of the records last_payment date field is the same as the YEAR for the CURRENDATE, i.e. the current year 2. The QUARTER of the last_payment date field is the same as the quarter we specify, e.g. 1 will be Jan1 to Mar31, 2 will be Apr1 to Jun30, etc. Hope that helps. But, if you need to show data for multiple quarters, then the second query I provided above would be better.
  22. Running two queries when you only need one? Also, why you you hard-code the data to determine the period to pull records for? Create a function and pass the quarter. function getQuarterResults($qtr) { $query = "SELECT SUM(amount_paid) as qRes FROM history WHERE YEAR(last_payment) = YEAR(CURDATE()) AND QUARTER(last_payment) = :q"; $stmt = $db->prepare($query); $stmt->bindValue(':q', $qtr, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetchAll(); return $result; } Heck you can even run one query to get the results for the entire year by quarter with one query. Plus, no need to prepare the query SELECT QUARTER(last_payment), SUM(amount_paid) as total FROM history WHERE YEAR(last_payment) = YEAR(CURDATE()) GROUP BY QUARTER(last_payment)
  23. Um, why do you have backticks around the dates? Use this: SELECT SUM(balances) FROM fiscalTable WHERE date BETWEEN DATE_FORMAT(NOW(), '%Y-01-01') AND DATE_FORMAT(NOW(), '%Y-03-30') EDIT: Barand beat me to it and had a better solution. Didn't realize there was a QUARTER() function.
  24. Based on the OP I don't think he can change the select fields. I would go with a header() redirect as cyberRobot suggested. <?php $parentAttendees = 0; //Determine how many parents will attend if(isset($_POST['oudersessieouder1']) && $_POST['oudersessieouder1']=='Ja') { $parentAttendees++; } if(isset($_POST['oudersessieouder2']) && $_POST['oudersessieouder2']=='Ja') { $parentAttendees++; } //Determine the page to redirect to if($parentAttendees==1) { //Redirect for one parent attendee $redirect = "pageForOneParentAttendees.php"; } elseif ($parentAttendees==2) { //Redirect for two parent attendees $redirect = "pageForTwoParentAttendees.php"; } else { //Redirect for No parent attendees $redirect = "pageForNoParentAttendees.php"; } //Perform the redirecr header("Location: {$redirect}"); exit(); ?>
  25. Depends, how many users do you expect to have the chat window open at any one time? What kind of server/infrastructure will you be using? For example, a shared server will not be able to support as many users as a dedicated server. But, let's be real here. I don't know what project you are working on. But, you are not going to go out with something and have a milling people logging in the next day. A 2 minute wait will be sufficient for whatever you are building right now and the probably users you will have. If and when it becomes an issue, you can tweak the process to check for updates to be more robust. As long as you write good, modularized code making such an update would be simple.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.