Jump to content

cpd

Members
  • Posts

    883
  • Joined

  • Last visited

  • Days Won

    5

Everything posted by cpd

  1. 1. I like the idea of cutting the processing when the data search has done it's job before the end of record, but am I really saving time or resources? If you have 1,000,000 records and cut it after 10 then yes you'll be saving time and potentially some resources - I couldn't comment on how much you'd save though. That said you're not guaranteed to save time or resources as the data you're looking for could be at the end of the array. Therefore you're efficiency is poor, see question 5. 2. Is it really a better idea to create a large array and pass it between modules or is grabbing the data from mySQL (perhaps cached?) a better choice? Passing a mass data structure containing all your data definitely is not more efficient than retrieving the data you need, when you need it. Assuming you're using an object-oriented style, you should fetch your data and and create an object to contain the data, then pass the object around. This object should contain appropriate methods with the appropriate visibility to ensure the attributes remain the property of said object and are not manipulated externally - unless this should be allowed. MySQL will cache the queries by default if I'm not mistaken, thereby optimising its efficiency. Furthermore, you can cache pages yourself where possible, even if its sections of pages although that begins getting complicated. 3. What is causing the pause in var_dump? Am I running out of RAM, perhaps going to virtual ram on my computer? Is there a way to assign memory to the array? Computers don't "switch to virtual RAM" if they run out of physical RAM [1][2]. There is no way to set memory in PHP as you would in Java for example (not to my knowledge anyway, someone can verify); PHP assigns memory at run-time. You may have hit a memory limit defined in your php.ini file; the variable is "memory_limit". If this is removed the operating system should enforce a memory limit per process but if you reach this you seriously need to rethink your application architecture. Hitting the PHP limit raises questions in itself. 4. Why is the nested foreach commands stopping output prematurely? Not entirely sure. You would need to break everything down and go through it sequentially debugging each line. 5. In terms of efficiency balanced by practicality, what is the best approach? You're current efficiency described using Big Oh notation is O(N^3) which is pretty horrendous, although not the worst. What this means is, if you submit data of size 1,000 to your algorithm the time taken to process the data will be 1,000 ^ 3 = 1,000,000,000. Similarly, if you have an input of 10,000 the time taken will be 10,000 ^ 3 = 1,000,000,000,000. As you can see, multiplying your input by 10 gives a massive difference in time taken for the algorithm to complete (x1000). To improve the efficiency you need to break your algorithm down and use the appropriate data structures to manage the data, e.g. Stack, Queue, LinkedList. Hopefully that answers your questions to some degree and if something I've written is wrong I hope someone corrects me! Sorry if I went off in a tangent or failed to answer your questions. [1] TechTarget. Virtual Memory http://searchstorage.techtarget.com/definition/virtual-memory. [2] Microsoft. What is virtual memory? http://windows.microsoft.com/en-gb/windows-vista/what-is-virtual-memory.
  2. Not true. You can set the cronjob to run every hour if you wanted. If you have lots of reminders then its obviously going to take longer with just a single server, but you can still do it. Think of google calendar (I'm not saying they use a cron but its a similar concept), they dispatch reminders to the minute and may use a cluster server for carrying out the task. Crontab is a program used to set up new cronjobs that are executed by the cron daemon on a linux machine (usually a server else the whole concept would be pretty pointless as normal computers are turned off regularly). What it executes is entirely up to you; you could execute a python script if you wanted, not just php. In your case you're going to be executing a PHP script that connects to a database, retrieves all the reminders for a given day, and sends an email to the user with a list of events. You could trigger the cron to go off in the early hours of the morning every day: 0 4 * * * php /home/account/private/crons/dispatchReminders.php For a guide on the crontab and how to use it you can go to http://crontab.org/. The tutorial you already have simplifies it quite a bit and abstracts the main content. The script you execute is completely separate from the script you use to display the reminders as they have two separate purposes. One is to dispatch reminders, the other is to display reminders to an end user using HTML in a web browser (just an example).
  3. Whats your purpose? Are you trying to encrypt data? And brackets wont affect array's since you're representing it as a string. It would be silly if it did affect it as you couldn't do anything, e.g. array("(Hello world)").
  4. Show us your code. We have no idea unless you do.
  5. If the username is unique you can use either. That said, if you want to use the ID to retrieve data without having to query the "user" table then yes, using the ID would be better. You just need to ensure your storing a uniquely identifying piece of data for that user.
  6. Don't run it as a cronjob at the moment. Just test it by putting it in your public directory and executing it through your browser. If you have SSH access just execute it via that.
  7. I'm pretty sure this is the second time you've asked this question and once again haven't been clear about it. Both times its appeared as thought you want to translate a document on-the-fly, think about what you're writing in future and even more so if English isn't your first language. The better we understand, the better we can help. Regarding your question: requinix's answer is the best you'll get. When someone sends a request to your server for the first time, set a default language to use - you could potentially set it based on the IP origin although this will be somewhat inaccurate. Store the language in a cookie for future use (Assuming you've got permission. If not, just set a session). Then overwrite the cookie/session each time they select a new language. You can then retrieve the content from your XML file based on the language they have selected, format the text however and serve up the formatted content. Client Server FileSystem | | | | First Request | | |------------------>| | | SetDefaLang | | | | | | GetXMLContent | | |------------------>| | | | | | Content | | |<------------------| | | | | SelectLang | | | | |SendContentWithCookie | |<------------------| | | | | | | | |SecReqWithLangCookie | |------------------>| | | UseCookieToGetContent | | | |
  8. Assuming you have a "user" table. Store their personal details in that, e.g. email. When a user logs in, set a session with their user ID that will be used to authorise the user when they try to access a restricted page. When the user makes a request for a restricted page, e.g. their details page, verify they're logged in by testing for the session(s) you set when/if they logged in.If they are logged in, retrieve the user details from the database and output them however you like. If they aren't logged in, redirect them to the login page. A login mechanism requires state and state is brought to the web using sessions and cookies. Follow the above relatively generalised method for all pages you want to restrict access to. You can google "login system php", "authentication system php" or anything along those lines to find out how its done.
  9. Why are you suppressing errors? Remove the @ and see if its spitting an error out.
  10. MySQL is a Relational Database Management System. From what you've described you should have only created 1 database with different tables; not multiple databases. It's essential you get your database correct before starting your application as it sets the building blocks. One question: if you're new to PHP but have managed to create a login script, why can't you continue researching to find out how to manage authenticated users within a website?
  11. We're all about helping solve problems. You have a problem, so post it and lets help you solve it... What code do you have? What is your issue? What steps have you taken to debug it yourself?
  12. You'll need to do some testing but I'd have thought file_get_contents() would return FALSE and not trigger an E_WARNING because you're retrieving a file using the File Transfer Protocol. I'm not 100% sure as to what the result is if it fails though so test it. Once you've found out what the trigger is, you can do something like: try { if($file === false) { throw new Exception("Message"); } } catch(Exception $e) { // Handle }
  13. Do you work for Microsoft or something or is the bak file creation public knowledge? First I heard of it...
  14. Good luck with that! You've got to read Microsofts bak file, how you do that I've no idea, I don't even know if its possible unless you know how it was created which I doubt you do.
  15. I've created a simple implementation of paginating content. It's okay but the __toString() method could do with being broken up and you could add additional customisations such as what tags the pagination will use. /** * A configuration object for the paginate class */ class PaginateConfig { /** * The URL the buttons should link to. This should contain the PAGE_NUM_REGEX * * @var string */ private $url = null; /** * The class to apply to the wrapper of the paginate * * @var string */ private $wrapperClass = null; /** * The class to apply to the numbers of the paginate * * @var string */ private $numberClass = null; /** * The class to apply to the buttons of the paginate * * @var string */ private $buttonClass = null; /** * Sets internal attributes. Will throw an Exception if it doesn't find a the Paginate::PAGE_NUM_REGEX * in the URL. * * @param string $url The URL to use for pagination * @param string $wrapperClass The wrapper class * @param string $numberClass The number class * @param string $buttonClass The button class */ public function __construct($url, $wrapperClass = null, $numberClass = null, $buttonClass = null) { $this->setUrl($url); $this->wrapperClass = $wrapperClass; $this->numberClass = $numberClass; $this->buttonClass = $buttonClass; } private function setUrl($url) { // Create an array to hold the matches and find matche $matches = array(); preg_match("/" . preg_quote(Paginate::PAGE_NUM_REGEX) . "/", $url, $matches); // If the matches array contains less than 2 elements throw an error if(count($matches) != 1) { throw new Exception("Could not find page number regex or there were too many occurences"); } $this->url = $url; } /** * Gets the URL * * @return string */ public function getUrl() { return $this->url; } /** * Gets the wrapper class * * @return string */ public function getWrapperClass() { return $this->wrapperClass; } /** * Gets the number lcass * * @return strnig */ public function getNumberClass() { return $this->numberClass; } /** * Gets the button class * * @return string */ public function getButtonClass() { return $this->buttonClass; } } /** * Geneates page numbers as links to flick through content */ class Paginate { /** * The regex paginate will look for to replace with a page number */ const PAGE_NUM_REGEX = "{:page}"; /** * The configuration of this Paginate * * @var PaginateConfig */ private $config = null; /** * The current page we're on * * @var int */ private $currentPage = null; /** * How many items per page * * @var int */ private $itemsPerPage = null; /** * The total items per page * * @var int */ private $totalItems = null; /** * The total pages available * * @var int */ private $totalPages = null; /** * Sets the internal attributes. * * @param int $currentPage The page we're currently on * @param int $itemsPerPage The total items per page * @param int $totalItems The total items * @param PaginateConfig $config The configuration to use */ public function __construct(PaginateConfig $config, $currentPage, $itemsPerPage, $totalItems) { $this->config = $config; $this->itemsPerPage = $itemsPerPage; $this->totalItems = $totalItems; $this->totalPages = ceil($totalItems / $itemsPerPage); $this->setCurrentPage($currentPage); } /** * Sets the paginate configuration * * @param PaginateConfig $config The configuraton to use */ public function setConfig(PaginateConfig $config) { $this->config = $config; } /** * Sets the current page. If the current page is less than 1 or greater than the total pages * the current page will be set to 1. * * @param int $page The current page */ private function setCurrentPage($page) { if($page > $this->totalPages || $page < 1) { $this->currentPage = 1; } else { $this->currentPage = $page; } } /** * Formats the URL provided by the configuration with the page number * * @param int $num The number to format the URL with * @return string The formatted URL */ private function formatUrl($num) { return preg_replace("/" . preg_quote(self::PAGE_NUM_REGEX) . "/", $num, $this->config->getUrl()); } /** * Generates the pagination adding any classes set in the configuration * * @return string */ public function __toString() { $class = array(); $class['wrapper'] = $this->config->getWrapperClass(); $class['number'] = $this->config->getNumberClass(); $class['button'] = $this->config->getButtonClass(); // Add the wrapper and previous page tags $output = "<div " . ($class['wrapper'] != null ? "class=\"" . $class['wrapper'] ."\"" : "") . ">"; $output.= "<a " . ($class['button'] != null ? "class=\"" . $class['button'] . "\"" : "") . " href=\"" . ($this->currentPage > 1 ? $this->currentPage-1 : 1) . "\">«</a>"; // Add the page for($i = 1; $i <= $this->totalPages; $i++) { $output.= "<a " . ($class['button'] != null ? "class=\"" . $class['button'] . "\"" : "") . " href=\"" . $this->formatUrl($i) . "\">" . $i . "</a>"; } // Add the next page and wrapper close tag $output.= "<a " . ($class['button'] != null ? "class=\"" . $class['button'] . "\"" : "") . " href=\"" . ($this->currentPage < $this->totalPages ? $this->currentPage+1 : $this->totalPages) . "\">»</a>"; $output.= "</div>"; return $output; } } $paginate = new Paginate( new PaginateConfig("http://www.domain.com/blog/" . Paginate::PAGE_NUM_REGEX), 6, 5, 16 ); echo $paginate;
  16. And an implementation with read-only access since you're not using an ORM and therefore the values shouldn't really be changed in this instance. /** * Represents a single record from a database */ abstract class Record { /** * Contains data set using the __set() method. * * @var array */ private $data = array(); /** * Sets a value when set as if its an attribute of this object. * * This is a default implementation and should be overriden if read-only access is requried. * * @param mixed $name The name of the attribute * @param mixed $value The value the attribute references */ public function __set($name, $value) { $this->data[$name] = $value; } /** * Gets a value as if it were an attribute of this object * * @param mixed $name The name of the attribute * @return mixed The value of the attribute * @throws Exception Thrown if the attribute couldn't be found */ public function __get($name) { $output = null; // Check if the variable is set, if not throw an exception if(isset($this->data[$name])) { $output = $this->data[$name]; } else { throw new Exception("Attribute not found"); } // Return the value return $output; } } abstract class ReadOnlyRecord extends Record { /** * Creates read-only access to this object */ public function __set($name, $value) { } /** * Allows child classes to set data internally still. This method should be used to * set any data within the scope of the object. * * @param string $name * @param string $value */ protected final function set($name, $value) { parent::__set($name, $value); } } /** * Represents a User within a database */ class User extends ReadOnlyRecord { /** * Sets the internal attributes * * @param int $userID * @param string $firstName * @param string $lastName */ public function __construct($userID, $firstName, $lastName) { $this->set('id', $userID); $this->set('firstName', $firstName); $this->set('lastName', $lastName); } } /** * Represents an Item within the database */ class Item extends ReadOnlyRecord { /** * Contains the user who created this item * * @var User */ private $user = null; /** * Sets the user who created this item and the item attributes * * @param User $user The user that created this item * @param int $itemId The item id * @param string $itemName The name of the item * @param string $itemImage The image associated with this item */ public function __construct(User $user, $itemId, $itemName, $itemImage) { $this->user = $user; $this->set('id', $itemId); $this->set('name', $itemName); $this->set('image', $itemImage); } /** * Gets the user who crated this item * * @return User */ public function getUser() { return $this->user; } } Both implementations get the items and display them. The logic for how many you display is elsewhere; you can use your query to manage this. My point here is instead of wrapping everything up into one big object, break it down.
  17. Okay we'll if you want to display all the items, and assuming you're not using an ORM, I'd have done something like /** * Represents a single record from a database */ abstract class Record { /** * Contains data set using the __set() method. * * @var array */ protected $data = array(); /** * Sets a value when set as if its an attribute of this object. * * This is a default implementation and should be overriden if read-only access is requried. * * @param mixed $name The name of the attribute * @param mixed $value The value the attribute references */ public function __set($name, $value) { $this->data[$name] = $value; } /** * Gets a value as if it were an attribute of this object * * @param mixed $name The name of the attribute * @return mixed The value of the attribute * @throws Exception Thrown if the attribute couldn't be found */ public function __get($name) { $output = null; // Check if the variable is set, if not throw an exception if(isset($this->data[$name])) { $output = $this->data[$name]; } else { throw new Exception("Attribute not found"); } // Return the value return $output; } } /** * Represents a User within a database */ class User extends Record { /** * Sets the internal attributes * * @param int $userID * @param string $firstName * @param string $lastName */ public function __construct($userID, $firstName, $lastName) { $this->id = $userID; $this->firstName = $firstName; $this->lastName = $lastName; } } /** * Represents an Item within the database */ class Item extends Record { /** * Contains the user who created this item * * @var User */ private $user = null; /** * Sets the user who created this item and the item attributes * * @param User $user The user that created this item * @param int $itemId The item id * @param string $itemName The name of the item * @param string $itemImage The image associated with this item */ public function __construct(User $user, $itemId, $itemName, $itemImage) { $this->user = $user; $this->id = $itemId; $this->name = $itemName; $this->image = $itemImage; } /** * Gets the user who crated this item * * @return User */ public function getUser() { return $this->user; } } $sql = "SELET Items JOIN Users..."; $result = ...; // Create an iterator for the items $iterator = new ArrayIterator(); // Loop through the results however you want depending on how you got the result while($row = mysqli_fetch_assoc($result)) { $iterator->append( new Item( new User( $row['userId'], $row['firstName'], $row['lastName'] ), $row['itemID'], $row['itemName'], $row['itemImage'] ); } <?php // Now within your HTML document you can do while($iterator->valid()) : $item = $iterator->current(); ?> Print out your HTML using the item E.g. <?=$item->id;?> <?=$item->getUser()->fisrtName;?> <?php $iterator->next(); endwhile; ?> This sort method would get all the users and create objects for them adding them to an iterator you can then cycle through to output the items. EDIT: Sorry for all the edits. Noticed I tried overriding a property and changing its visibility which isn't allowed.
  18. Why are you using Visual Studio to create databases? Its only just registered what you're doing. Use SQL Server Management Studio to administrate the database. Its free to download and is built specifically to manage SQL Server.
  19. Okay so you want to select all the items from the "item" table (whatever you called it) and join the user table. Then display the results. (This assumes you're using a database to store the items and users. You can add the requirement to view no more than 24 items per page. Does that make sense?
  20. So list a few requirements as you've semi done already. The user will be able to view a list of all items The user will be able to view the title of an item The user will be able to view the price of an item The user will be able to view the image associated with an item (verify number 1) Do we want to view who created the item? Are we taking this from the person who uploaded the items perspective? If so should they only see their items? If not I assume its from anybodies perspective and as such they can see all items? These questions will affect the logic in our system. We aren't concerned with the way it looks at the moment, we just need the logic to retrieve what the requirements state we need the user to see.
  21. Well you want to display the results of the query we just verified yes? If so, you need to cycle through the result set, like you did in your debugging, and print out the HTML with the values you've retrieved. E.g. <?php while($row = mysql_fetch_assoc($getRecent)) : ?> <tr> <td><?=$row['someValue'];?></td> <td><?=$row['anotherValue'];?></td> <td><?=$row['fooBar'];?></td> </tr> <?php endwhile; ?> I can't see you trying to loop through the results anywhere in your script.
  22. Brilliant. So you've now verified through a series of debugging steps the data you're retrieving is correct therefore, the query is correct and doesn't need adjusting. You did that yourself with a bit of guidance - not that hard is it? Where else do you think the problem could be? Are you even attempting to display these results within your page?
  23. So you want to display all the "item images" and "item titles" for each item? Are the items purchased by users or something? What does the key ID and value ID represent in your map above? E.g. your key ID represents a customer and the value ID is the ID of an item they purchased.
  24. Well done. Do yourself a favor and make it easier to read by putting echo '<pre>'; above the while loop. Now verify the output is consistent with your database entries, i.e. its only retrieving posts with a type of 1. If so you know your query is correct.
  25. Nice work setting the test up. You've obviously copied & pasted my code as the typo was there. The error tells us there's a syntax error on line 6, so we should review line 6 to see if anything is wrong. Typical syntax mistakes include 1) forgetting a semi colon; 2) not closing brackets - all variations; 3) misspelling variable/function names. One of the above is your problem.
×
×
  • 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.