Skip to content


New home page

I just finished setting up a new home page… I think this way it looks much better, more professional :)

Posted in Web Development.


How To Check Web Page Last Update

Many times we come across websites or blogs where the dates of the posts are not displayed or made hidden so that a person doesn’t come to know when that page was last updated.soal

With this simple trick you can come to know when a specific Web page was last updated.kenyit

This trick is proven to work for every web page and has been personally tested by me on Internet Explorer, Firefox, Safari, Google Chrome, and Opera.

To determine when a page was last updated, follow these simple steps:

01. Open the page for which you want to get the information. Like for me its I333
i333 homepage

02. Clear the address bar [where you type the address of the sites]:
clear address bar

and type or copy/paste from below:

paste javascipt

03. Press Enter or Go button:
press enter or ok

and Voila! a message box will come up displaying the date and time of the last update of that particular page:
message box

Press the OK button to remove the notification and continue browsing.
press ok button

This way you can know When Was A Web Page Last Updated.’ Hope you enjoyed it!senyum

Source

Posted in Uncategorized.


Web Nerd Terminology (Explained)

Great post from Chris Coyier

As happens with any weird niche societal group, us web nerds have developed some language of our own. Some of this language is perfectly acceptable English, but still sounds weird to an outsider. I thought I’d throw together a list of these words and attempt to explain them in plain English as a reference for non-nerds.

Browser – A browser is a software application that is used to visit websites. Firefox, Internet Explorer, Safari, etc. If you think this is obvious, think again.

Server – When a webpage is visited, data is sent from some computer somewhere to your computer over the internet. That other computer is a server, essentially just like the one you are looking at, only specially configured to deliver information to other computers asking for it. Even though any computer could technically be a server, far more commonly people purchase server functionality from companies that specialize in it, like Media Temple.

URL – Uniform Resource Locator – is one of those things like this: http://css-tricks.com/video-screencasts/64-building-a-photo-gallery/ Some people also use URI – Uniform Resource Identifier – for the same purpose, although URL is far more common. I honestly read the entire Wikipedia article for both and I still don’t really understand the difference. A domain name is the first part of the example above: css-tricks.com. Anybody can purchase a domain name, from companies like Go Daddy that specialize in it.

Tag are text that go around content in HTML code to identify the type of content they surround. For example, in this code <li>Go dancing.</li>, the tags are <li> and </li>.

Anchor – An “anchor” tag is a tag that looks like this in HTML code: <a href=”http//url.com”>link text</a>. Most HTML tags are referred to by what they look like, for example, a <ul> tag would likely be called an “Yoo-Ell” tag out-loud. The reason anchor is used is because it sounds weird both written and spoken to say “An a tag”.

Wrapping refers to putting an opening and closing tag around content in HTML code. If you hear “You’ll need to wrap it in an extra div,” they mean that whatever content area is being referenced needs to have a <div> tag added before it and an </div> tag added after it.

Nesting is a lot like wrapping but implies being several layers deep. For example, this is a series of “nested” divs:

<div id="outer">     <div id="inner">        <div class="section">        </div>     </div>  </div>

Borked – Something is wrong, usually used in reference to the visual layout of a webpage. “The sidebar dropped down and borked the layout.”

Markup – Markup is just another way of saying HTML code, but is slightly more generic and may also be used to reference XML or other “describing” languages. If you hear a phrase like “The site uses very semantic markup”, that means that the website’s HTML code uses very appropriate tags to describe the content it displays, which is a desirable and sometimes difficult thing to do.

Accessibility – When accessibility is talked about in reference to websites, it means how easy or difficult it is to access the content for people with disabilities. For example, how easy it is for mobility impaired uses to navigate the site, blind users to read the site, or colorblind people to differentiate links from regular text.

Usability – Usability is similar to accessibility but differs in that it refers to ease of use for all visitors, not limited to disabled people. For example, a site that requires lengthy registration to view content or that has navigation that is in different places on different pages may be considered to have bad usability.

Findability – Findability is a subset of usability and refers to how easily users can locate the content they are looking for on a website. Often a elusively difficult task.

Validation – It is possible, even probable, that code contains mistakes. But who says what constitutes a mistake in code? When it comes to HTML and CSS, the W3C does. They offer tools to run these types of code through to check for errors. If it there are no errors, the code passes and is said to be valid code (or “markup”!) ALTERNATIVELY, validation can refer to data. For example, if you enter a phone number that is 5 digits long, software might “validate” that data and reject it as invalid.

Standards – This again refers to the W3C, the organization that puts forth the “rules” describing how browsers should behave in interpreting code. Can you imagine how difficult any job would be if everything you did you had to repeat five different times with slight variations? That’s what web standards are trying to prevent, buy putting forth rules so that everyone’s job is easier things only need to be done one way. If you hear someone say they “write standards compliant code”, it probably means the code they write validates, but hopefully it also means they have an understanding of the importance of web standards and fight for them.

Semantics – The word itself generally refers to the meaning of words or word choice. On the web, semantics means choosing the correct HTML tags to describe to content. For example, using table tags to lay out your site isn’t very semantic because those tags don’t relay any meaning to the content they contain. Whereas, a tag like <navigation> is extremely semantic.

Rendering is the process the browser goes through when interpreting HTML and CSS and turning that into the visual end result you see on your screen.

Client-Side refers to a language that is interpreted by the browser itself. For example, JavaScript is downloaded by your browser and then run locally on your machine. Your browser is the “client”.

Server-Side refers to a language that is interpreted by the server. For example, PHP is interpreted by your server, processed, and then delivered to you. As an easy example to remember the difference, if you ask a client-side language to display what time it is, it will display the time set on your computer. If you ask a server-side language to display what time it is, it will display the time set on the server.

DOCTYPE – This is the gibberish looking code at the top of HTML documents that looks something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

There are a number of different ones. They tell the browser what specific set of rules should be followed when interpreting the rest of the code in the document.

Copy – It just means text. “I need some copy for that” means “I need the text that you want to go in that area.”

White Space – Areas of a design (not necessarily white!) that are intentionally left blank for aesthetics.

Vector – A form of graphic where the design is saved as points and mathematical formulas. Because of this, the files are “resolution independent” meaning they can be scaled to any size without losing their crispness. Adobe Illustrator files are vector files (although it is possible for them to contain bitmap data). AI, EPS

Bitmap – A form of graphic that is saved as individual pixels, meaning it has a set resolution and cannot be scaled up or down without affecting its crispness. Adobe Photoshop files are bitmap files (although it is possible for them to contain vector data). JPG, GIF, PNG.

Analytics – Means data about the usage of a website. How many people viewed the website that day? What countries were they from? What browser did they use? How long did they stay? Those are questions Analytic data can answer. It is gathered by using special software built for capturing it, like Google Analytics.

Kerning – Adjusting the spacing between two specific letters, to improve how a word looks aesthetically. Tracking is similar but refers to overall letter spacing.

Sprite – An image that actually contains multiple images. The images are typically displayed cropped down to only show a small area. As counter-intuitive as it seems, this can improve efficiency by requiring less total images to be used.

Elastic – is a type of web layout where font sizes and widths are declared with a special unit of measurement called an Em (an abstract concept just meaning “relative size”). This allows for the entire web layout to scale up and down, rather than just the font size. This differs from a Fixed Layout where theoretically the width of the site would stay the same and just the text would scale up and down or a Fluid Layout where the width of the layout is determined by the browser window.

Framework – Generic term to describe software that is built to simplify things. For example: RoR , or Ruby on Rails, a development framework designed to help creating applications on the web easier.

 

Acronyms

CSS – Cascading Style Sheets – a file ending in .css, which is linked to from the HTML, which controls the look of the rendered page.

HTML – Hyper Text Mark-up Language is the code that forms all websites and describes the content it contains. It is important to understand that ALL websites end up as some form of HTML, regardless of the languages used to build them. For example, a file might be PHP (Hypertext Preprocessor), as in index.php, but ultimately what is served up to the browser is HTML. The file extension PHP just lets the server know to process any of the special PHP code inside before serving it up.

JS – JavaScript – a client-side language with the unique ability to A) watch for events (e.g. mouse clicks, key presses, etc) and B) make things happen on a webpage without a page refresh. For example if you see a button on a website that you click and a new area slides down, that’s (probably) JavaScript.

AJAX – Asynchronous JavaScript and XML – A popular technique of loading content from a server and placing it onto a page without the need for a page refresh. This has grown to be an extremely popular technique for building websites that are more responsive and feel more like desktop applications. While AJAX is still technically an acronym, it usually doesn’t have a heck of a lot to do with XML.

CMS – Content Management System – a software program that runs on a server with the purpose of making managing the content on the website easier. For example, a site may have hundreds of pages (like this one). Each of those pages does not exist as a separate HTML file. Instead, the content is kept in a database and injected into templates and served up as needed by the CMS.

SEO – Search Engine Optimization – Doing things to a website specifically to rank higher in searches done on search engines like Google. On the web, traffic = money, and search engines drive big traffic, hence the big desire for everyone to rank as highly as they can.

SERP – Search Engine Request Page – You search for something in Google, you get a page of results, that a SERP.

TLD – Top Level Domain – .com, .net, .org … there are a lot of them.

CRUD – Create, Read, Update, Delete – generally used to describe a web application with the primary purpose of doing those things. Think of blog software, where you can Create a blog entry, Update or Delete it later, and the Front-End of the site Reads it to display it.

DOM – Document Object Model – is a bit of an abstract concept. It is the system browsers use to represent and interact with the objects (elements) in HTML. For example, that DIV in your HTML is definitely part of the DOM, but so is the browser window itself and it’s immediate page history. Maybe the easiest way to think about it is that it’s basically the HTML that makes up your page, plus a bunch of more stuff that only web nerds care about.

RGB – Red Green Blue – The color model that is used by electronic media to display graphics. Commonly used to describe the “mode” an image is saved in. Images used for electronic display (web, video, etc) should be RGB.

CMYK – Cyan Magenta Yellow Black – The color model used by traditional 4-color printing. Photo-realism can be achieved by printing only these four colors. Commonly used to describe the “mode” an image is saved in. Images ultimately being used to be printed on paper should be in CMYK.

RSS – Really Simple Syndication is a special (and standards based) form of XML for publishing content. For example, most blogs provide RSS of their content. Other people (even basic users) can take that RSS and use it in different ways, like republishing that content elsewhere, or just reading it through special programs, like Google Reader). May be referred to an an RSS Feed, or even just Feed by itself.

DPI / PPI – Dots Per Inch and Pixels Per Inch. “Dots” are literally physical dots of ink on paper, determining the resolution of a print image. “Pixels” are bits of data, determining the size of an electronic image. Commonly swapped and used incorrectly.

WYSIWYG – What You See Is What You Get – Describes anything where you interact with the visual end result rather than an abstraction. For example, a font menu that shows what the fonts actually look like is a WYSIWYG font menu. A web design program that allows you to place boxes and drag them around is a WYSIWYG program.

SVN – Subversion – A system for maintaining different versions of code. Changes are “checked in” and can be “rolled back” to previous versions (in the case of problems).

 

Phrases

Above the Fold – This comes from the newspaper industry, where the space on the top half of the front page is far more valuable than the space below it. On the web, content that is visible without scrolling is referred to as above the fold, and is also more valuable (as in, to advertisers or just generally for users attention).

Browser Safe – or “Web Safe” refers to a specific set of colors that, in the long long ago, would be acceptable to use because they would display properly on all computer monitors. No longer very relevant.

Hover State – When your mouse cursor rolls over a link, and that link changes color, that is the links “hover state”. A mockup web design might contain both a buttons regular state and hover state. Differs slightly from Active State – which is a the circumstance a link would be in if, for example, the link was “tabbed to” in a browser.

Back End – Generically refers to anything going on “behind the scenes” of a website. There are all kinds of things that happen on complex websites underneath what people actually view in their browsers. A CMS is an example of a “Back-End”.

Front End – The part of a web application that people visiting the site in a browser see. Essentially the “website” part of a website.

Slicing a PSD – Phrase used to describe the process of converting a Photoshop document (PSD) into an HTML/CSS website. There is a “slice tool” in Photoshop, which can be a part of this process, but not necessarily.

Pixel Perfect – A finished web design that matches perfectly the mockup from which it was created.

Browser Zooming is a feature in browsers where entire website are magnified, rather than just text resizing. Somewhat controversial, as it can cause Horizontal Scroll, a situation where a websites content is wider than the browser window meaning that a user would have to move the scroll bar left and right as well as up and down to browser content.

Posted in Uncategorized.


WordPress Plugins: Implementing jQuery Tutorial

Utilizing ajax and other wonders within WordPress plugins couldn’t be easier thanks to jQuery. What’s more, jQuery is already installed as part of the WordPress installation (At least it is with version 2.7), so its even easier to implement! This tutorial will guide you through the steps on including the jQuery library within your plugin so that you can use all the goodness jQuery can bring, setting up your own javascript file, as well as an important tip at the end!

Including the jQuery library

Before you write any ajax code you need to include the jQuery library, so that it is loaded as part of your WordPress pages. You need to do three things:

  1. Create your own javascript file for your ajax code.
  2. Write a function that loads your javascript file and the jQuery library.
  3. Add an action to call the aforementioned function.

So, in your plugin directory, create a folder called “js”, and within that folder create a file called “myJavascript.js”. Now, in your main plugin PHP script, create the following function:

1.function my_init() {
2.wp_enqueue_script( ‘myJavascript’,get_bloginfo(’wpurl’).’/wp-content/plugins/YourPluginName/js/myJavascript.js’, array(’jquery’));
3.}

This function does a couple of things – 1) it points to your javascript file which you will update later, and (2) it also invokes jQuery to be loaded with it.

So now we have the function, we need to tell the plugin to call that function when the page is loaded. We do this by adding a new action, so add the following to your main PHP script of your plugin:

1.add_action('init', 'my_init');

This action will now ensure jQuery and your javascript are called in the <HEAD> part of your pages. All you now need to do is write your ajax code in your newly created “myJavascript.js” and you’re done!

VERY important note

When writing your jQuery code, you must use jQuery(”#DIV”) or jQuery.get() – emphasis on the jQuery rather than using $(”#DIV”) or $.get – Using $ will not work as its already been set aside by the javascript library “Prototype” which is also used by WordPress. It is case sensitive too, so no jquery or Jquery!!

Download

Download Icon

I have written the code up into a small plugin which you can view and install. Download it here. Unzip and install the folder “jQuery_WordPress_Plugin” to your “/wp-content/plugins/” directory. Full details are included in the my_plugin.php file.

Also See

Check out the tutorial on implementing custom CSS into a WordPress plugin

Source

Posted in JQuery, PHP, Programming, Web Development, WordPress, javascript.


Deploying a CakePHP app with Capistrano

Password-less login

First we need to be able to login without providing a password this guide from Brian Rosner describes the steps to do this.
The reason for this password-less login is that you don’t have to provide a password when you deploy this way.

Capistrano

Next we need to get Capistrano. I work on a mac with OSX 10.5, witch has Capistrano built-in. If you have never updated this version of capistrano you might want to gem update your version.

Folder structure

capistrano folder structure
The image above shows my folder structure. The current folder is actually a symlink to the latest deploy of my project. The logs is for my apache access and error logs and the releases folder contains the latest 10 releases deployed to the server.

The shared folder contains files and folders that i want to use instead the ones i deploy. In my case i keep the /app/config folder here.

Capfile

In the root of my project folder i created a capfile (no extension)

that contains the following code:

load 'deploy' if respond_to?(:namespace) # cap2 differentiator  role :web, 'example.com'  ssh_options[:username] = 'notrootofcourse'  ssh_options[:forward_agent] = true    set :scm, :git  set :scm_verbose, true  set :repository, 'git@git.example.com:repository'  set :branch, 'master'  set :deploy_via, :remote_cache  set :use_sudo, false  set :application, 'application_name'  set :deploy_to, "/data/webservers/#{application}/"    namespace :deploy do    task :start do    end        task :stop do    end        task :restart do    end      desc <<-DESC      Symlinks shared configuration and directories into the latest release      Also clear persistent and model cache    DESC    task :finalize_update do      run "rm -rf #{latest_release}/app/config; ln -s #{shared_path}/app/config #{latest_release}/app/config"      run "rm -rf #{latest_release}/app/tmp/models/*"      run "rm -rf #{latest_release}/app/tmp/persistent/*"    end          end    namespace :tail do    task :default do      run "tail -f #{deploy_to}/logs/*.log"    end  end

The first lines of the Capfile set some global configuration options, like your ssh username that can login without providing a password, the (in my case git) repository to pull the latest release from and the name and path of the application.

To make capistrano work with (Cake)PHP you need to overwrite all the default tasks that capistrano runs when deploying. Since i use apache and php, we don’t need to restart the webserver, so we just create a :restart task that does nothing, the same goes for :start and :stop

in the :finalize_update task i link the /config dir of my CakePHP app to the shared folder i described above. This way i always use the live configurations instead of my dev configs. Also, just to be sure, i remove the cached data.

All there is to do is a “cap deploy” in the root folder of your project and capistrano will deploy the latest version to your server.

This is of course just a simple example of a capistrano config and you can create your own folder structure and run your own commands.

Besides deploying i also created a :tail namespace, witch tails my log files. This way i can do a “cap tail” to see what’s going on with apache without logging in trough ssh. Other possible functions could be a “cap clearcache” to remove all the cache files.

source

Posted in CakePHP, Linux, PHP, Programming, Ruby, Scripting, Web Development.

Tagged with , , , .


love is patient

Posted in Design.

Tagged with .


PHP for Beginners: Building Your First Simple CMS

The Magic of PHP + MySQL


It’s safe to say that nearly every website that’s up-to-date these days is using some form of content management system (CMS). While there are a ton of great free options that provide us with a CMS to power a website (Wordpress, Drupal, etc.), it doesn’t hurt to peek under the hood and get a feel for how these systems work.

To get our feet wet as back-end developers, we’ll be creating a simple PHP class that will:

  • Create a database
  • Connect to a database
  • Display a form with two fields
  • Save the form data in the database
  • Display the saved data from the database

 

 

This class is intended to give you a feel for how PHP and MySQL interact together, and to show the basics of a CMS. I’ll be skipping explanations of some of the very basic programming stuff, so if at any point you feel lost, head on over to w3schools.com and give yourself a crash-course in PHP. I’ll try not to lose anyone, though, I promise.

Building the Class


Our first step is to simply lay out the class in a file named ’simpleCMS.php’ so we have a road map to work with.

<?php    class simpleCMS {    var $host;    var $username;    var $password;    var $table;      public function display_public() {      }      public function display_admin() {      }      public function write() {      }      public function connect() {      }      private function buildDB() {      }  }    ?>

As you can see, we’re creating one class with four variables and five methods. I’ve opted to use PHP’s object-oriented approach because it makes for cleaner code in large projects, and, in my opinion, it’s just good practice.

The Variables

In this case, all four variables are for connecting to the database: $host, $username, $password, and $table provide a path and access to our database on the server. For now, we’ll leave those empty and move on to our database, which is constructed by the method buildDB().

Build the Database

private function buildDB() {      $sql = <<<MySQL_QUERY          CREATE TABLE IF NOT EXISTS testDB (              title	VARCHAR(150),              bodytext	TEXT,              created	VARCHAR(100)      )      MySQL_QUERY;        return mysql_query($sql);  }

This function runs a MySQL command that checks the database to see if testDB exists. If so, it simply passes along a notification of success; if not, it creates our table and assigns three columns to hold data.

Connect to the Database


Now that we have a function to build our table, let’s create the function that will connect to our database.

public function connect() {      mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());      mysql_select_db($this->table) or die("Could not select database. " . mysql_error());        return $this->buildDB();  }

We call mysql_connect() to hook into our database, and then mysql_select_db() to make sure we save our data in the right place. Both of these functions are accompanied by the die() command, which essentially says, “in the event that this function fails, stop execution of this script and display a message.”

Our connect() function connects to the database and gets us pointed in the right direction, then runs our buildDB() function. Remember the grammatically awkward “IF NOT EXISTS” part of our MySQL command? Because we’re going to run this function every time the page is loaded, we have to make sure we’re not overwriting our database with every function call, and that’s exactly what that phrase requires.

Build the Form

So, we’ve got a database. Now we just need to put stuff in it!

public function display_admin() {      return <<<ADMIN_FORM        <form action="{$_SERVER['PHP_SELF']}" method="post">        <label for="title">Title:</label>        <input name="title" id="title" type="text" maxlength="150" />        <label for="bodytext">Body Text:</label>        <textarea name="bodytext" id="bodytext"></textarea>        <input type="submit" value="Create This Entry!" />      </form>    ADMIN_FORM;    }

Again, this is a very simple function. When called, it simply returns the HTML markup to create our form. You’ll notice, however, in the action attribute of the form element, that I’ve used the variable $_SERVER['PHP_SELF']. This is, essentially, a shortcut that references the file you’re currently using (in our case, it’s display.php). This is useful if you’ll be reusing your code across a site and don’t necessarily want to rewrite this function for each page.

I’m also going to take a second right now to talk about the method I’m using to return the HTML. It’s a format used in PHP called HEREDOC syntax, and I love it.

The primary advantage of HEREDOC is that it allows you to include formatting in your output. This is extraordinarily useful for folks like me who take issue with cluttered source code. You can read more about HEREDOC syntax and its ilk in the PHP manual.

Saving the Data to the Database

Our form will allow us to input information, so how do we save it? That’s where our write() method comes in.

public function write($p) {      if ( $p['title'] )        $title = mysql_real_escape_string($p['title']);      if ( $p['bodytext'])        $bodytext = mysql_real_escape_string($p['bodytext']);      if ( $title && $bodytext ) {        $created = time();        $sql = "INSERT INTO testDB VALUES('$title','$bodytext','$created')";        return mysql_query($sql);      } else {        return false;      }  }

Let’s start with the function call itself—we’re passing a variable to this one, which we haven’t done so far. Our variable $p is going to hold the information sent from our form via the post method.

Once inside the function, we start with a conditional statement that’s checking to see if the the title value was set in the form before it was submitted, and if so, we’re setting our $title variable to the $_POST['title'] value (NOTE: we’re using the function mysql_real_escape_string() as a precaution against potentially dangerous input, which is important to keep in mind when you’re building anything that will allow users to input information). If $_POST['title'] wasn’t set, we skip this line, leaving the $title variable unset.

This process is repeated for our second input, and then both variables are checked to make sure nothing is blank before saving to the database. If both variables are set, we then set the $created variable with the current Unix timestamp, which we’ll use to sort our entries chronologically when we view them in the future.

We now have three variables, and because we’ve run checks, we know that all three variables are not empty. Now we can write our MySQL query that will save the entry in the database!

Displaying the Information from the Database


Now that we have the means to put information into our database, we need to create a way to get that information back out. This is where display_public() comes in. This is by far the most complex of our methods, so let’s really take our time and figure out what’s going on inside.

public function display_public() {      $q = "SELECT * FROM testDB ORDER BY created DESC LIMIT 3";      $r = mysql_query($q);        if ( $r !== false && mysql_num_rows($r) > 0 ) {        while ( $a = mysql_fetch_assoc($r) ) {          $title = stripslashes($a['title']);          $bodytext = stripslashes($a['bodytext']);            $entry_display .= <<<ENTRY_DISPLAY        <h2>$title</h2>      <p>        $bodytext      </p>    ENTRY_DISPLAY;        }      } else {        $entry_display = <<<ENTRY_DISPLAY        <h2>This Page Is Under Construction</h2>      <p>        No entries have been made on this page.        Please check back soon, or click the        link below to add an entry!      </p>    ENTRY_DISPLAY;      }      $entry_display .= <<<ADMIN_OPTION        <p class="admin_link">        <a href="{$_SERVER['PHP_SELF']}?admin=1">Add a New Entry</a>      </p>    ADMIN_OPTION;        return $entry_display;    }

The first thing to note when reading from a database is the way PHP and MySQL interact with each other. First, we ask the database a question (query), to which it replies with a result (resource). However, this result isn’t really useful until we’ve decoded it using one of several methods that “fetch,” or organize, the information that’s contained inside into a usable form (array).

Our very first action in the above function is to set up our query in the variable $q. The asterisk (*) operator in MySQL means “everything,” so our query is asking the database to select everything from entries in the table testDB in reverse chronological order, limited to the first three entries returned.

Now that the query is defined, we send it to the database using the function mysql_query(). The resulting resource is stored in the variable $r. This is where it gets a bit tricky.

We now run a conditional statement that says, “IF mysql_query() didn’t fail, AND IF the number of entries returned was greater than zero, process the result, OR ELSE display a default message.”

If $r contains entries from the database, we now have to “fetch” that data. Information from the database is returned as an array, which is organized similarly to the database table itself. The function mysql_fetch_assoc() will take the resource and break each entry into an associative array (this means that when we save the result of mysql_fetch_assoc() into the variable $a, the data from the entry will be accessible by the column names in the database, i.e. $a['title']).

However, mysql_fetch_assoc() only gives us one entry at a time. To get all of the returned entries, we have to use a while loop. Essentially, we’re saying, “WHILE $r has values we haven’t used yet, get the next entry in line and do the following actions with it.”

In this case, we’re going to check the entry to make sure that data was returned, then remove the slashes that were added when we saved the information to the database using stripslashes(). After that, we simply wrap the variables in some HTML and, voila! we’ve got screen-ready content!

As a final step, the code adds a link to the bottom that allows users to add an entry. It’s worth noting the use of the “.=” operator used in the while loop and when creating the “Add a New Entry” link; a function can only return one variable, so we need to append the new information to the existing variable. If we just used the equals sign (”=”), we would overwrite existing data and end up with just a link to the form and no content.

So, you’ve now written your first CMS class! You can easily write and retrieve data to and from a database. All that’s left to do is to try it out!

Using the Class

To use our class, we need to create a separate file. I’m going to call it “display.php”, which I’ll save in the main web folder, with our class saved as “simpleCMS.php” in a folder called “_class” within the main folder. To start, we just set up a document with plain ol’ HTML.

<html>      <head>      <title>SimpleCMS</title>    </head>      <body>      </body>    </html>

To use our class, we just have to insert a little PHP between the body tags:

<?php      include_once('_class/simpleCMS.php');    $obj = new simpleCMS();    $obj->host = 'database.host.net';    $obj->username = 'DB1234567';    $obj->password = 'DBpassword';    $obj->table = 'DB1234567';    $obj->connect();      if ( $_POST )      $obj->write($_POST);      echo ( $_GET['admin'] == 1 ) ? $obj->display_admin() : $obj->display_public();    ?>

First and foremost, we have to include the class using the include_once() function. Then, we have to instantiate our object so that our code knows what’s going on. Third, we set all of those variables we talked about toward the beginning of this tutorial. You’ll have to replace all of those values with the information you get from your own server or hosting company. And fourth, we connect to our database using the connect() method.

After we’ve connected to the database, we check to see if any $_POST information exists. This is because we’re using the same file for input, processing, and display of information. If anything was passed via $_POST, we run the write() function to validate it and save it to the database. Then, we use some shorthand trickery to run a conditional statement. In essence, we’re saying, “IF $_GET['admin'] is set to 1, then show the form using display_admin(), OR ELSE show me the stored entries using display_public().”

And that’s it! Once you get a feel for it, this sort of basic programming will allow you to start exercising total control over websites you build, whether you decide to really dig in and build your own CMS framework or just improve an existing CMS by, say, writing a Wordpress plugin.

Really, when it comes to modern web design, you should have at least some understanding of how things are working behind the curtain—understanding how a site works will better enable you to design sites that have a more fluid integration of form and function. And besides, adding PHP and MySQL to your curriculum vitae definitely won’t hurt your credibility…

 

 

Jason Lengstorf runs Ennui Design, a freelance design and development effort. He has a fetish for building custom applications from scratch, including his own content management system. When he’s not glued to his keyboard, he’s likely to be wearing cowboy shirts, deadlifting, or pretending to know stuff about wine.

Important Note

This code is written for demonstration purposes only. Several security holes have been pointed out in the comments, which I have addressed in Part Two of this tutorial series. Still, I would strongly advise not using it for production websites without further testing. The demo has been removed.

I have covered some of the bases with security, but other issues may exist. Further reading on security risks and safe PHP code can be found here. Please read through this before implementing this code on your server to avoid potential security holes.

Source

Posted in Mysql, PHP, Programming, SQL, Web Development.


Adam Wiggins and Ryan Tomayko, Heroku

An interview in 3 parts with Adam Wiggins and Ryan Tomayko of Heroku from their recent visit to New Relic. They discuss the vision behind the creation of Heroku, their passion for helping developers create scalable, high-performance Rails apps in the cloud, taking full advantage of cloud deployment, and their tips and best practices to create a high-performance app.

Part One: Introductions + The Heroku Vision
Play Video (52.5 MB, 8:51, QuickTime MOV)

Part Two: Performance + Best Practices
Play Video (70.3 MB, 12:14, QuickTime MOV)

Part Three: Tools + Collaboration
Play Video (39.2 MB, 6:46, QuickTime MOV)

Posted in Ruby.


How does CSS work in CakePhp?

To use cakephp’s framework to the fullest, you need to utilize its conventions. To modify the default template for your site copy:

/cake/libs/view/templates/layouts/default.thtml   to /app/views/layouts/

You then edit that copied file. The presence of

/app/views/layouts/default.thtml

tells cake to stop looking at the old layout and look at the new one.

So you’d think that it would work the same way with css. Well almost. You don’t need to copy the css file, it’s already there for you in

/app/webroot/css/cake.generic.css

Ok great. Just delete that and copy your new css over the old stuff right? No, that’s not a great idea. If you do that you’ll lose all the cool cakephp css classes that you may want to take advantage of later on. For example ‘required’ and ‘optional’ classes for your form labels. Let’s keep the generic css and overwrite it’s classes as we need them.

How do we do that? Let’s go to the default.thtml and we’ll see:

$html->css('cake.generic');

That’s the same as putting

<link rel="stylesheet" type="text/css"   href="/ProjectPath/css/cake.generic.css" />

In your html code. Well that’s not exactly what we want to use because we want to use the @import url code to import our css files rather than link them.
Luckily the HtmlHelper::css function has an import option. So we use:
$html->css(’cake.custom’, import);

which yields :

@import url(ProjectPath/css/cake.custom.css);

between style tags.
Now that you have an idea of how the html helper css function works you can check out how to auto-load your css files for each controller.

Source

Posted in CakePHP, PHP, Web Development.


Control Panel Mail Icon Missing Windows 2008 server x64

Go to Control Panel and click on View View 32-bit Control Panel Items and after that you can see the Mail Icon.

If still you are not able to see the Mail Icon or you are using Windows Vista 32-Bits, then the Outlook is not set as default program for e-mail. To set the Outlook as default email program, do the following steps: –

  1. Go to Control Panel
  2. Click on View Classic Icons
  3. Click on Set Default Programs
  4. Select the Microsoft Office Outlook in the list in left side.
  5. Now, click on Set this Program as default.

Posted in Hacks.