Jump to content

Fadion

Members
  • Posts

    1,710
  • Joined

  • Last visited

Posts posted by Fadion

  1. Most probably you'll need to trim() the lines before checking their contents. There may be spaces before or after the dot, so it doesn't return true when compared to "."

     

    The following code works fine. I used a foreach() instead of a for().

     

    <?php
    $lines = file('txt_files/read_this.txt');
    
    foreach ($lines as $line)
    {
    if (trim($line) == '.') break;
    
    echo $line;
    }
    ?>
    

  2. My previous post should have given you the reply. As you're coding with objects, you should have the basic understanding on how they're initialized. Anyway, replace the static call to the user class with a typical object initialization:

     

    $users = new Users;
    $users->count();
    

     

    I'm also seeing a lot of global calls ($db) that don't really make sense in class context where you're trying to separate concerns. There are better ways to manage dependencies. For your groups class:

     

    <?php
    class Groups
    {
    
         protected $db;
         protected $users;
    
         public function __construct (Database $database, Users $users)
         {
              $this->db = $database;
              $this->users = $users;
         }
    
         public function whatever_method ()
         {
              $this->db->fetchRow("some query"); 
         }
    
    }
    
    $groups = new Groups(new Database, new Users);
    $groups->whatever_method();
    ?>
    

  3. Routers are pretty much standart. Explode the uri, iterate, check for directories, if class exists, if it has that method and so on. Don't worry too much about efficiency because the overhead is generally minimal.

     

    Basically, you'll need to go over each uri piece and check first if it's a directory. If it is, append it to the current working directory (a variable that has the base). Next check if a controller file and class exist with the uri piece. Finally, check if that class has the method. Some defaults can be set, for example when no method is set, you can search for the "index" method. Reflection can also be useful to check if a class has a method, if it's public and if any arguments need to be passed (uri parameters can be mapped to method arguments).

     

    Writing a full-fledged example in here would be too long. However, you can take a look at a router I've build for my framework. It's simple enough to be easily understood and it has all the bells and whistles.

  4. You'll need to set the inputs values to the post/get data, so they get filled automatically on submit. Supposing you're sending the form via post:

     

    <input type="text" name="full_name" value="<?php echo $_POST['full_name']; ?>">
    <input type="text" name="email" value="<?php echo $_POST['email']; ?>">
    

  5. With a good setup and some supporting hardware, 1m rows shouldn't be a big issue.

     

    First try "EXPLAIN"ing the query/queries and check if they're using those indexes. Be sure to index the "SELECT"ed fields too, so MySQL uses the indexed fields only.

     

    Next, on caching, there are several options. In my experience, APC does a very good job and is quite easy to install and use. It's primarily an opcode cacher, meaning that it will cache the compiled PHP script until it's modified, but offers setting and getting cache variables. I doubt the opcode cacher will give you any boost when the bottleneck is in the database, but what you can do is cache the result sets so they're not computed on each search.

     

    Let me give a simple example:

    <?php
    $search = 'some search'; // the search keywords
    
    if (apc_exists($search))
    {
         // get the results from the cache
         $results = apc_fetch($search);
    }
    else
    {
         // run the query and make the computations
         // results are passed to $results
         apc_store($search, $results);
    }
    ?>
    

     

    That's a very basic caching based on keywords, where one search is run once and served from memory on the next calls. However, you can build your own strategies, like caching popular searches and so on.

     

    The other option would be using a pure caching solution like Memcached (which can be used as a distributed solution) and Redis. These are powerful key->value, shared, memory-based storage engines. Basically, they run as daemons and accept connections from any script, sharing data between them. Usage is pretty much the same as with APC.

     

    As final words, keep in mind that caching depends completely on RAM and it gets filled up pretty fast. The amount you have wired in should be enough to run the PHP scripts, execute the database queries and have some space for caching too. It should be easy to find recommendations online (or from someone in this forum) for the hardware you need depending on the load, number of queries and how much you'll cache. In these days, with the cheap hardware costs for vps/dedicated, it's a lot easier to scale than to optimize. Especially if you don't have the experience for the later.

  6. It is happening because #content has a fixed height and it generally isn't a good idea for items that make the flow of the document.  In the meantime, #left-sidebar may become higher than those 500px of #content and there you have a problem.

     

    First, you'll need to put that #left-sidebar in the document flow by a clearfix solution. The easiest way could be to add an "overflow: hidden;" property to #content, but beware that it will cut off any other elements. Next, remove the "height" of #content completely or if you really need to set a specific height, at least use "min-height".

     

    I would write your rules as follows:

     

    #content
    {
         background: #fff;
         width: 95%;
         padding: 30px 0 0 10px;
         overflow: hidden;
    }
    
    #left-sidebar
    {
         width: 15%;
         float: left;
         background: #ccc;
         padding: 20px 40px 20px 20px;
         margin: 10px 60px 10px 30px;
    }
    

     

    text-align: center and height: auto are the default values. Check if it works.

  7. It's not clear what you're asking, but I'll just make a guess that you want a simple 2 columns layout with a content area and a sidebar.

     

    <header></header>
    <div class="wrapper">
         <div class="content"></div>
         <div class="sidebar"></div>
    </div>
    <footer></footer>
    

     

    div.content { width: 60%; float:left; }
    div.sidebar { width: 30%; float:right; }
    

  8. I'm afraid you'll need to read some more information as most probably the concepts that make a MVC application are yet confusing. Anyway, I'll try to answer your questions again.

     

    Clean URIs and Routing

    As the Router maps URI pieces to controllers and controller methods (which I like to call "actions"), they're quite linked with each other. They work well together by having a defined format for the URI that can be parsed and transformed into pieces. If you create an URI with multiple GET parameters, there's no good and automated way of mapping it.

     

    A normal URI that goes well with the Router is:

    index.php/products/show/25/

     

    It's widely used because the index.php part isn't that bad, even if the user can't rewrite the URI. With rewriting, "index.php" can be removed and the URI becomes a little nicer. As you can see, the complete URI is just a string which can be exploded by "/" and turned into an array. From that, the Router can read each piece and determine what to do:

     

    /products/ => The router will search for a controller class named "products".

    /show/ => The router will search for a "show" method of the "products" controller. If this wasn't set, index() or start() or whatever would be called.

    /25/ => Is a parameter that the Router doesn't care for. It can be retrieved by a URI helper that fetches URI segments.

     

    That's the very basic idea of how a Router works with clean (I would call them SEF - Search Engine Friendly) URIs. A lot more can be done to add features to Routing, but the main concept is that.

     

    Recreation of controller objects and Views that share data

    On a typical MVC application, only one controller is called per instance. From the previous example, /products/show/ will only run the "products" controller. When the users goes to /orders/, yet again only the "orders" controller will be called. So, there's no controller recreation when you call once a single one.

     

    It's almost true for views too, but those can have included files or inheritance in some template engines. However, the idea is pretty much the same as with controllers. The "products" controller will open the "products" view, send parameters to it (query results included) and finally render it.

  9. As you say you're new to PHP and programming in general, I'd suggest to try an already established framework. There are so many out there you can chose, starting from microframeworks like Slim and to big ones like ZF2, Symfony or Yii. Somewhere in-between you'll find CodeIgniter, Laravel or FuelPHP. It is a good idea to understand how a framework works before thinking of rolling your own; even if it's a simple one.

     

    I'll try answering your questions.

     

    First of all, you'll need a router that is responsible for mapping URIs to controllers and controller actions. Basically, it will get the URI, explode it into pieces and check if a controller and action exist.

     

    Let's assume you have this URI:

    site.com/index.php/users/ - which can be rewritten (mod_rewrite) to - site.com/users/

     

    The first piece of the URI can be treated as a controller, so the Router knows that it should find controllers/users.php. If no second piece if set, it will call the "action_index" method.

     

    Now the URI becomes:

    site.com/users/add/

     

    The second piece is treated as the controller action and the Router knows that it should find a method (action_add) inside the Users controller. In this way, you can create CRUD operations easily and organize them logically.

     

    To answer your question number 1 (and 2 I guess), yes, it is normal for everything to pass into index.php as it is the only access point into the application. However, that file shouldn't contain any logic on how things are done; it just does basic includes and runs any class that should be initialized (like the router). Try separating concerns as much as possible.

     

    Question number 3 is answered above. You shouldn't give all responsibilities to start() or any other, single method for that matter. A controller can do a lot of things and doing all of that in a single method is overkill. Adding users should belong to users/add. Deleting to users/delete and so on.

     

    Question number 4 is a typical MVC one, because people forget what Models are for. You can easily reuse queries by writing them inside your models. Any controller that needs some certain data, can take them from the model. Don't write SQL code more than once because it'll become a pain to maintain (no rhyme intended). Anyway, you will need to pass the query results (fetched array) to the view each time you use it. Views aren't supposed to read directly from models; it is the controller who passes variables to it, query results included.

     

    As I mentioned in the beginning, you should get some knowledge from other frameworks, on object oriented principles, design patterns and so on. You need those information not just to create a framework, but to get a better understanding of how applications can be created. It's quite difficult for someone to give you all the information you need to create a framework because it's too much for a simple forum post.

  10. jQuery's $.ajax() has e beforeSend method that is triggered just before the AJAX call is made and is a good way to show a preloader image. It would look like this in your code:

     

    $.ajax({
        url: '..',
        type: '..',
        beforeSend: function() {
            $('#loading_image').show();
        }
        complete: function() {
            $('#loading_image').hide();
        }
    });
    

     

    Hope it helps.

  11. Are you having any errors or it's just that you have no idea on how to print results from MySQL? It isn't clear at all.

     

    First of all, you'll need to escape input to prevent sql injections. After that, it's as simple as working with arrays.

     

    <?php
    if ($_GET)
    {
    $color = mysql_real_escape_string($_GET['color']);
    $color2 = mysql_real_escape_string($_GET['color2']);
    
    $results = mysql_query("SELECT * FROM tbl WHERE color='$color' AND color2=$color2");
    $values = mysql_fetch_assoc($results);
    
    echo $values['id'].'<br>';
    echo $values['color'].'<br>';
    echo $values['color2'].'<br>';
    }
    ?>
    

  12. The place I work does work for some big companies who still use IE6. I don't like it, but it's not my choice. Besides that, my test was run on IE 9.

     

    The ever repeating Internet Explorer 6 debate.

     

    Sure, they use IE6 so monolithic, proprietary, expensive and not-updated-since-the-90s web applications can work. I've been there and I know that, but those types of visitors aren't the ones the web expects today. When someone uses a browser that's a decade old (which is technically equal to a millenium), it's certain they don't care much about the web. Should we?

     

    From W3Counter statistics, IE6 has a global share of only 2.28%. If I remember right, China is the world leader in IE6 usage and if that's true, it lowers the percentage locally to Europe, USA and other countries. Even if that wasn't true, 2.28% is very low for us to care.

     

    As for the tests, I run them successfully in IE7 and IE8. Don't have IE9 right now to test, but I doubt the browser behavior has changed...

  13. I'm posting directly two solutions to your problem.

     

    1) Using Javascript to generate a random code. Not sure what type of code it is, but I assumed it's a simple rand(min, max). It can be worked on if you know a bit of JS.

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    <script type="text/javascript">
    	$(document).ready(function(){
    		$('#code-button').click(function(){
    			random = generateRandom(1000, 10000);
    			$('#code').val(random);
    
    			return false;
    		});
    
    		/*
    		**	From Mozilla Developer Center
    		**  https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
    		*/
    		function generateRandom (min, max) {
    			return Math.floor(Math.random() * (max - min + 1)) + min;
    		}
    	});
    </script>
    </head>
    <body>
    <form method="post">
    	<input type="text" name="code" id="code"><br>
    	<input type="text" name="email"><br>
    	<input type="text" name="mobile"><br>
    
    	<button type="submit">Send Form</button>
    	<button id="code-button">Generate Code</button>
    </form>
    </body>
    </html>
    

     

    2) Using Javascript once again, but this time the code is generated by PHP and the response is fetched with AJAX. It's practically the same thing, as I've used rand() to generate the code, but it may suit your case better depending on the complexity of the generated code.

     

    I just changed the Javascript a bit and left the HTML code from above intact.

    $(document).ready(function(){
    $('#code-button').click(function(){
    	$.get('generate_code.php', function(data) {
    		$('#code').val(data);
    	});
    
    	return false;
    });
    });
    

     

    generate_code.php, which gets called by Javascript has just one line of code:

    <?php
    echo rand(1000, 10000);
    ?>
    

     

    Hope this helps.

  14. If it's a submit button inside the form, it will always submit the form. You have to use an <input type="button"> or a <button> and handle the event with Javascript. I would suggest you generate the code with Javascript (directly with JS code or with an AJAX call) too, so the page doesn't get refreshed at all. jQuery would help on it a lot.

     

    If you want help with code, just ask.

  15.  

    I thought IE6 was dead?! In IE7+ it works fine. I would rather not support IE6 than provide a Javascript hack. Form submission would be the smallest problem anyway.

     

    PS: You made me run Parallels (virtual machine) just to test that thing. I like debate, but this one is completely pointless. It's a standart solution vs a Javascript solution. I've nothing against JS, because I do use it on a daily basis, but it's just wrong making a standart form submission be relied only on it. Anyway, anyone has his/her own way of thinking.

  16. teynon solution looks fine to me, but I think you're not getting it quite right or you're aiming for something completely different (wich I'm not understanding).

     

    The code you have checks if any of the database fields is empty and if only one of them is empty (Logical OR), the code will fallback to the "else" part, showing everything as "empty". I guess what you want is: if one of the database fields is empty, it will show as "empty" without affecting all the others. And that's what tenyon's solution does! Basically, you check all the fields individually if they're empty or not: if yes, give them a value of "empty"; if not, leave them as their are. It makes total sense!

  17. The problem with the button solution is that the user can push enter to submit the form. Then neither would be registered. The reality is, if you wan't to be paranoid about making it right, you should make two separate form pages.

     

    Actually the first button will be added to POST data when the form is submitted, either by pressing the button or just submitting the form via keyboard (pressing enter). I wouldn't have posted that solution if it would have such a big usability issue. The way the browser puts data to POST, by adding the first button and not the second is strange and I'm unable to explain technically, but it gets the job done :)

  18. The "No results found" shows when $expiration_date is lower than $today, right? That means that it doesn't even go to the UPDATE code.

     

    What database class you're using? Anyway, the idea would be to loop through the results, or you'll get only the first row. In each loop iteration, calling $result->fetch_assoc() should bring up the same row. Normally, you should have:

     

    <?php
    while ($rows = $result->fetch_assoc()) {
         $id = $row['id'];
         //etc...
    }
    ?>
    

  19. The form can have only one action attribute and as such, only one PHP script to send the form data. It's not a limitation, but something logical, because such things are not HTML's responsibility.

     

    What you can do is use the same processing script (phpcode1.php), but in there add some logic to make different actions depending on which button was pressed. Create a form like the one below first:

     

    <form action="http://localhost/smatrix/phptest/phpcode1.php" name="optionsform" method="post">
         <input type="checkbox" name="criteria[]" value="box1">
         <input type="checkbox" name="criteria[]" value="box2">
    
         <button type="submit" name="button1">First Button</button>
         <button type="submit" name="button2">Second Button</button>
    </form>
    

     

    The <button> isn't included in POST if it wasn't clicked, which makes it interesting for your needs. You can see what button was pressed just by checking if it exists in the $_POST superglobal. So, in phpcode1.php you could have:

     

    <?php
    if (isset($_POST['button1'])) {
         //logic when button 1 is pressed
    } else  {
         //logic when button 2 is pressed
    }
    ?>
    

     

    Hope that helps.

×
×
  • 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.