Jump to content
Larry Ullman's Book Forums

Antonio Conte

Members
  • Posts

    1084
  • Joined

  • Last visited

  • Days Won

    126

Everything posted by Antonio Conte

  1. You better check it out, Jon. I recently implemented a shopping cart solution in under 500 lines of application code. While it was really limited to functionality, it had support for Users, categories, products, sales and general cart functionality. Throw a Stripe facade on top of that (I recently implemented one) and you have a functional Ecommerce-solution. No need to code anymore really. The packages used where Sentry, (for User auth) Eloquent (The awesome ORM shipped with Laravel). The job I built this for fell through, but I gained invaluable experience. Composer can't get enough praise from me.
  2. Check your primary key size settings on your tables. I.e INT(11). I had a similar problem a couple of years ago, and allowing larger integers solved the problem. Try doing a manual insert into the DB using PHPMyAdmin.
  3. Also remember that PHP is an interpreted language. That means that PHP code is executed by a interpreter, not from a compiled source. The file extension .php has no special functionality. The interpreter might also run .html, .txt or .randomExtension as PHP if you can just tell PHP and Apache to treat it that way. This article might clear some things up: http://php.about.com/od/advancedphp/p/html_php.htm
  4. I've been using composer for a while know, but I felt like participating a little bit too. On a hobby project I needed a priorityQueue, and noticed SPL had one. The problem was that it would dequeue values in random order if several nodes share the same priority. Usually, this is considered a bug for a PriorityQueue, so I decided to fix that. Here the very small ThomasLarsson/PriorityQueue hosted on Packagist! And here's a small preview of how I'm using the package. Anyone else played around with composer, submitted a package or think this is interesting?
  5. Another solution to the problem would be to save the div name to a variable outside of the loop, and run a simple if-clause against it. An example could be. $header = false; $group = false; foreach ( $menuRows as $section => $type ) { // Check if header is equal to last if ( $header && $header !== $type['div_name'] ) { echo $type['div_name']; } // Check group if ( $group && $group !== $type['grp_name'] ) { echo "<tr><th>" . $type['grp_name'] . "</th><th> </th><th> </th><th> </th></tr>"; } // Check item (what I gathered) if ( $header && $header !== $type['div_name'] ) { echo "<tr><td><strong>" . $item['title'] . "</strong>" . $item['descr'] . "</td><td>" . $item['price'] . "</td><td>" . $item['price2'] . "</td><td>" . $item['price3'] . "</td></tr>"; } // Save latest header and group $header = $type['div_name']; $group !== $type['grp_name']; } I haven't tested the code, but the logic to use is something like that. Considering that the code is really ugly and undreadable, recursion might be your best bet. Increasing readability for a little performance is no big deal. Especially when the data is so small. Btw, I recommend you skipping in and out of PHP when your HTML is so tangled with your logic. Something like this perhaps: <?php foreach ($menuRows as $section => $type) : ?> <h3><?= $type['div_name']; ?></h3> <table> <tr> <th><?= $type['grp_name']; ?></th> <th> </th> <th> </th> <th> </th> </tr> <?php foreach ($menuRows as $menu => $item) : ?> <?php if ($item['div_name'] == $type['div_name']) : ?> <tr> <td><strong><?= $item['title']; ?></strong><?= $item['descr']; ?></td> <td><?= $item['price']; ?></td> <td><?= $item['price2']; ?></td> <td><?= $item['price3']; ?></td> </tr> <?php endif; ?> <?php endwhile; ?> </table> <?php endwhile; ?>
  6. The short answer is yes. Without looking at any code, and from your description, a recursive function might do. The "problem" might also be that you structure you data in a bad way, so that you are forced to work with recursive functions. I can only speculate, but I do believe such a problem should be solvable without recursion. I would at least look into that before settling on your current solution. Give us some database structures, example data and code to work with if you need further help.
  7. Textmate has gained much "hype" recently due to experienced developers Using it alongside the command line in YouTube learning videos. What it boils down to is efficiency, and most would gain from using an IDE in that regard. NetBeans checks my code, generates Class skeletons, runs my tests, generates my Apis, formats my code, push code to github, uploads to my server Using FTP and has my favorite shortcuts for code generation. It also has built in support for all languages I program in. Textmate can't beat that. IDEs are not for everyone though. I would at least recommend you giving one a try. You can easily change back later on, and the possible gain is huge.
  8. A good technique you can pick up from the MVC pattern is how you should structure your code. When I program procedurally, I generally never include HTML before the end of the document. That way, you can keep logic and the rending of HTML separate. You can try to make your program follow these steps: 1. Include/require all the libraries, files with functions, etc you need. 2. Call functions and save their results to variables 3. Determine what "view" (i.e login error view or successful user dashboard) 4. Include (render) the views for the page. <?php // 1. Require needed files require ('./includes/config.inc.php'); require (MYSQL); require ('./includes/form_functions.inc.php'); // (1.1) Include the SQL login logic as a "Model function" instead of placing logic here require './models/authenticate.php'; // 2. Make function instead of walls of code (Notice the $dbc database variable) $login_errors = performAuthentification($dbc, $_POST['email'], $_POST['password']); // 3. Set data prior to rendering views $page_title = 'Connect au Cop.com'; //Registration title name // 4. Check which view to render $load_view = ( empty ($login_errors) ) ? 'views/user/dashboard.php' : 'views/errors/login_failed.php'; // 5. Render view files: include './includes/header.php'; include $load_view; include './includes/footer.php';
  9. phpstuff: Stop immediately and download Eclipse, Netbeans or another of the free IDEs. It's totally worth it.
  10. I'm mearly guessing here, but I think the index will really only slow down your INSERT / UPDATE queries, but not affect SELECT or DELETE. Slow inserts are often not really problematic — it's the select queries you want to go fast. Another guess would be that SELECT queries will actually be quicker due to your index, as indexes builds binary trees (b-trees) on your data. It's pretty much boils down to this: How does SELECT queries against the 15 columned uniquely indexed table compared to other queries to other tables? You'll get execution times in PHPMyAdmin. Larry might know more about this than me.
  11. It's ok and nothing really unusual to do. If it should be unique, add indexes as necassary. DBMS are incredible potent, and you don't really need to focus heavily on performance unless you work with really large data. A good tip is to focus on data integrity first, then focus on performance if things start going slow. The "correct" way here would be to work with IDs rather than names, but unless you need the three tables dogs, kennels and breeders, you don't really need to enforce that. The principle is called normalization, and teaches you how data should be split into the correct table entities. Good luck, Buttercream.
  12. You can find some good information here: http://dev.mysql.com/doc/refman/5.0/en/create-index.html To give you an example on last name, you could do something like this: CREATE INDEX partially_lastname_index ON users (lastname(5)); Keep in mind that you are mainly saving diskspace limiting the index. Unless that's important, you'd generally want to index the whole column. I trust that you've already done some research though.
  13. There is no "YII best practice". This is totally related to CSS, HTML and front-end design, and has nothing to do with YII or PHP in general. The way you want to do this is by overriding CSS. CSS is read top-to-bottom, and newer (declared later) )CSS properties overwrites older ones. (more to the top) I'll give you a concrete example using main.css and style.css. main.css: .something { margin: 10px; border: 1px gray; color: blue; } style.css: .something { margin: 15px; border: 1px black; padding: 5px; } If style.css is loaded later in the HTML file than main.css, the class .something from style.css will overwrite the properties from main.css. That means it will change the margin to 15px and have a black border. The class will also have a padding of 5px, and have blue text. This means you can basicly target anything main.css does in style.css. The reason why you want to do this is because you can then update main.css without losing any changes, and still override the styles. Does that make sense?
  14. A quick tip is to apply some debugging. $permission = $user->canEditPage(new Page($_GET['id'] )); var_dump($permission); if( ! $permission ) { header("Location:index.php"); exit(); } What does something like that give you?
  15. You should really be using composer rather than downloading manually. It probably has lots of dependences, and it would be a pain in the butt to keep it all up-to-date. The composer.json here: https://github.com/zendframework/ZendSearch/blob/master/composer.json
  16. This is my .htaccess for Codeigniter: RewriteEngine on RewriteCond $1 !^(index\.php|images|assets|uploads|robots\.txt) RewriteRule ^(.*)$ /index.php/$1 [L] It routes everything to index.php (remote index.php in CI config) but ignores the folders images, assets and uploads. Give it a shot.
  17. Nice you got it working. Also, don't sweat it too much. There's always "some better way" to do things, but we must all start out somewhere. Gradually improve your code as you learn more, and make sure to enjoy the learning processes. I'll take some time to explain the query now. Some part of the key is the aliasing. When you use several tables in a query, adding the AS alias is often required. When a column has the same name in several tables (as your student_no) MySQL will need to know which table the column is in. The same is true for aggregation functions (UPPER(column)) as echo $row['UPPER(column)'] looks a bit clumsy. The next part is the FROM part. A join will basically gather data from two tables that share an identifier. In this case that is student_no. It's the ON (student.student_no = course.student_no) part that illustrates that shared identifier. All rows from the student table will be linked to rows from the corresponding course table it shares that identifier with. The exact same thing happens with the student and score tables at the next line. The where part limits the search to ONE specific student_no. If you remove the WHERE clause, you'll see ALL students linked with data from the two other tables. However, you need to specify what columns to display from the results we have. Because of our aliases, (you are free to choose the alias yourself) prefixing anything with student.column will look in the student table, courses.column in the courses alias (course_attendance) and scores.column in the scores alias (toeic_scores). SELECT student.student_no, course.student_no and scores.student_no will therefor display the student_no column from the respective tables. Lastly, the LEFT OUTER JOIN specifies HOW the joining is done. This join type will use the LEFT table as a base. You can think of the table used in FROM table as the left most, and the last JOIN line as the right. In this example, the student table is the base for the joining of the tables. The OUTER part will use the base inclusive and use rows from the student table even if no match is found in the "right" table. The normal way is exclusive, where student rows without matching course or score rows would be ignored. JOIN is just the basic keyword. In other words, this is valid. This would however make an exclusive match. FROM student AS s JOIN course_attendance AS c ON (s.student_no = c.student_no) You won't likely ever need to write a more advance query than this. I very seldom do. Hope that made some parts of it less scary. If you have phpMyAdmin, I would recommend you to run the query there. It'll make it more clear to have it "visualized"
  18. A better way to do this would be to write a more advanced query. That way, you can get more information from a single query. // Build query $query = "SELECT student.*, UPPER(student.school) AS uschool, UPPER(student.campus) AS ucampus, COUNT(course.student_no) AS attempts, COUNT(scores.student_no) AS attendance FROM student AS student LEFT OUTER JOIN course_attendance AS course ON (student.student_no = course.student_no) LEFT OUTER JOIN toeic_scores AS scores ON (student.student_no = scores.student_no) WHERE student.student_no = $id ORDER BY $order ASC"; // Get result $result = mysqli_query($dbc, $query); while ( $row = mysqli_fetch_array($result)) { echo $row['uschool']; // Uppercased shool name echo $row['ucampus']; // Uppercase campus name echo $row['attemps']; // Number of attemps echo $row['attendance']; // Number of attendances } I don't really have the time to explain this to much, but try it out an play with it. I bet you can use it for something clever. I'll reply later on if you have any questions. Btw. I guess the reason why your code don't work is because of variable scope. You can't use a variable inside a function without: 1. Passing it as a parameter 2. Declaring it a global variable $dbc = ''; // DBC variable; mysqliSomething1( ); // Declared global mysqliSomething2($dbc); // Pass as variable mysqliSomething3( ); // Unavailable function mysqliSomething1() { global $dbc; // Declare it global // We can use $dbc here now. } function mysqliSomething2( $dbc ) { // $dbc as a paramter. We can use it now } function mysqliSomething3() { // $dbc unavailable here }
  19. You over think performance gains here. Don't focus on the 5% optimizations, but those that really drag your execution time down. The keyword in that regard is loops. If you write a function that iterate an array once, your performance is called O(N). If execution on 1000 array Elements is 3 seconds, doubling to 2000 will execute in 6 (linear increase). If you nest another loop into your first, you'll get O(N2). If 1000 elements takes 3 seconds, 2000 will take 9. (Exponential growth) Nest even one more, and you'll have an exponential growth. If 1000 elements takes 3 seconds, 2000 will take 27... Performance is also never the only consideration. You sacrifice performance for code clarity, organization, structure, time to develop, etc. If performance is the only consideration, none of us would play around with PHP. My suggestion is focus on performance when you really need it. If you are really interested, read about Big-O analysis as it's clearly the most important code optimization. General tip: Avoid the extra loops if you can help it. If you ever nest two or more loops, (having three or more loops in total) a red light should flash. Don't run DB queries in loops.
  20. Go into the structure view in phpmyadmin and change both to lowercase. Why would you ever let the structures differ anyway?
  21. Sure the code reponsible for that is not in register-thanks.php? I see nothing that would send an email here.
  22. Method overloading is such a beautiful tool, and I really wish PHP could implement it. Such a shame.
  23. Ok. I will check it out. I've provided a workaround be using one of the cookies that stores the user id. Using that, I simply do a query against phpBB3 to get the needed information. While I know this is not secure by any stretch of the imagination, the information returned is harmless, and only includes username, birthday and email_address - all public information non-the-less. The solution will work until I figure out how to make the cURL request work. EDIT: I've almost managed to make this work. The first time I load the page after the cURL request, the correct data is returned. However, when I refresh once more, I receive the anonymous information again. In the mean time, I'm logged out of phpBB3 the next time I visit because the session validation then fails. Some new code to check: private function phpBB() { $url = 'http://forum.juvenorge.com/getLoggedInUserInfo.php'; $remote = 'REMOTE_ADDR: ' . $_SERVER["REMOTE_ADDR"]; $agent = 'HTTP_X_FORWARDED_FOR: ' . $_SERVER['HTTP_USER_AGENT']; $strCookie = $this->spoofCookie(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, false ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // User session info curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HTTPHEADER, array($remote, $agent)); curl_setopt($ch, CURLOPT_COOKIE, $strCookie ); curl_setopt($ch, CURLOPT_COOKIEJAR, $strCookie ); curl_setopt($ch, CURLOPT_COOKIEFILE, $strCookie ); $output = curl_exec($ch); curl_close($ch); return $output; } private function spoofCookie() { $k = 'phpBB3_***_k'; $u = 'phpBB3_***_u'; $sid = 'phpBB3_***_sid'; $ck = $k.'='.$_COOKIE[$k].'; '; $cu = $u.'='.$_COOKIE[$u].'; '; $csid = $sid.'='.$_COOKIE[$sid].'; '; return $ck . $cu . $csid . 'expires=Saturday, 20-Mar-2014 01:34:06 GMT; path=/; domain=.juvenorge.com'; } Some interesting discoveries. After checking phpBB3's admin panel, I've noticed some security option of interest. For a session to be deemed valid, it must pass the following checks: IP validation. It will match the whole IP address against the one saved in the DB Session table Browser validation: It will match information of the browser against the session. HTTP X_FORWARDED_FOR header validation: This must match for the session to continue I'm not currently sure how all this is validated but I'm digging for answers. It seems like I'm almost able to get it to work. Very promising.
×
×
  • Create New...