Showing posts with label URL. Show all posts
Showing posts with label URL. Show all posts

Feb 3, 2012

Learn CakePHP From Novice to Professional : Part 2

Model-View-Controller


Cake enforces an MVC structure for your web applications. Basically, it effectively separates typical operations into specific areas:















MODELS :for all your database interaction
VIEWS :for all your output and displays
CONTROLLERS :for all your commands/scripts for input and program flow

The typical PHP application mixes each of these three functions in the same code, making it difficult to maintain and debug.

The typical flow for PHP scripting

This is the typical flow for PHP scripting (see Figure 1-1):

  1. The client sends a request to a PHP script by typing a URL or clicking a link of some kind.

  2. The script processes the data and then sends the database requests directly to the database.

  3. The script receives any database output and processes the data.

  4. The script generates output and forwards it to the client’s browser.


In short, everything is contained in one PHP script. By using the include() function, developers strip out common functions into other external files, which makes it possible to reduce redundancy. The most complex PHP applications use objects that can be called anywhere in the application and modified depending on the variables and settings passed to them. Developers, when using objects and classes, can structure the application in numerous ways.

MVC improves upon the typical PHP flow and is an effective technique for making class objects available over the whole application. The main goal behind MVC is to make sure that each function of the application is written once and only once, thus streamlining code by reducing redundancy. Cake accomplishes this goal by not only providing the resources to make MVC possible but also by using a consistent method for where to store operations in the application. Simply naming your own files a certain way allows Cake to piece together the various resources without using any code specifications.

How Cake makes use of the MVC structure

MVC can vary depending on the framework with which you’re working, but generally it works as follows (see Figure 1-2):

  1. The client sends a page request to the application, either by typing a URL or by clicking a link of some kind. By convention, a typical URL is usually structured like this:
    http://{Domain}.com/{Application}/{Controller}/{Action}/{Parameter 1, etc.}


  2. The dispatcher script parses the URL structure and determines which controller to execute. It also passes along any actions and parameters to the controller.

  3. The function in the controller may need to handle more data than just the parameters forwarded by the dispatcher. It will send database requests to the model script.

  4. The model script determines how to interact with the database using the requests submitted by the controller. It may run queries with the database and do all sorts of handy data-sorting instructions.

  5. Once the model has pulled any data from or sent data to the database, it returns its output to the controller.

  6. The controller processes the data and outputs to the view file.

  7. The view adds any design or display data to the controller output and sends its output to the client’s browser.


The benefit of using MVC to develop web sites is that repeated functions or tasks can be separated, thus allowing for quicker edits. It can even help in debugging. Say an error keeps occurring during the interaction with the database. Usually the problem will be somewhere in a model. Knowing that all database interactions occur in just one place makes it easier to solve problems.

Nov 14, 2011

Wordpress Multiple Category Search

Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works.

So finally decided to go more into deep of wordpress and php, and came up with a code which works.

Functioning of this code:  Searches all posts using a custom search box where 2 drop-down box will be displayed with values of categories in it.

Have you ever played with search URL? Or tags URL or Categories URL?

Very few might have knowledge that wordpress supports multiple tags or multiple categories. Don’t believe me, in your URL, type this

http://yourblog.com/tag/tag1+tag2

Or

http://yourblog.com/tag/tag1,tag2

Now what does this means? Simple when you type tag1+tag2 it will show you posts with having both the tags. And when you type tag1, tag2 it will show you all the posts having either tag in it.

Same works for categories.

http://yourblog.com/category/cat1+cat2
http://yourblog.com/category/cat1,cat2

Now I tried this same functionality in search URL of Wordpress.

http://yourblog.com/?s=html&cat=114

And woila it worked!!!!

Here “s” is your search term and “cat=114” is your category ID. This will work and display all the posts with the search term only in category ID 114.

But the only problem in this is that it will just take one category at a time.

Wordpress doesn’t supports this URL

http://yourblog.com/?s=html&cat=114+115

Here comes a big problem. After a lot of search I found that “+” is considered as a space in URL. So we need to write a function which will make this space act as a + operator.



[php]
add_action( 'parse_request', 'category_search_logic', 11 );
function category_search_logic( $query ) {
if ( ! isset( $query->query_vars[ 'cat' ] ) )
return $query;
// split cat query on a space to get IDs separated by '+' in URL
$cats = explode( ' ', $query->query_vars[ 'cat' ] );
if ( count( $cats ) > 1 ) {
unset( $query->query_vars[ 'cat' ] );
$query->query_vars[ 'category__and' ] = $cats;
}
return $query;
}

function check()
{
$url = $_SERVER["REQUEST_URI"];
$query = str_replace('&cats=', '+', $url);
if(isset($query) && ($query != $url))
{
header('Location:'.$query);
}
}

add_action('parse_query', 'check');
[/php]

After getting this function in our functions.php file, the multiple categories URL with search will work.

So it’s time to design a simple search form.

Paste this anywhere in your theme.



[html]
<!-- Search Form -->
<div style="margin:10px 0 10px 0;">
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<table cellspacing="5">
<tr>
<td>
<label for="s" style="margin:10px;">Search</label>
</td>

<td>
<input type="text" class="field" name="s" style="width: 100px;"/>
</td>
<td>
<?php wp_dropdown_categories('show_count=1&hierarchical=1'); ?>
</td>
<td>
<?php wp_dropdown_categories('show_count=1&hierarchical=1&name=cats'); ?>
</td>
<td>
<input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" style="display: block; position: relative; top: 7px;"/>
</td>
</tr>
</table>
</form>
</div>
<!-- Search Form -->


[/html]

That’s it, now just go and try your wordpress site will be having a multiple category search option. No plugin and no hundred lines of code, and best part, it’s fully flexible to use. If you want one more category drop down then just copy paste the category php code one more time.




Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif


Now we will add basic html code into our index.php file

[html]

<body>
<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>
</div>

</body>

[/html]

Now comes the main AJAX code.

Inside your head tag, add the following code:

[html]

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
{
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
{
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
return;
}
else{
$('#name').removeClass('error');
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

$.ajax({
url : 'data.php', //Declaration of file, in which we will send the data
data:{
"name" : term_name                //we are passing the name value in URL
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);
}
});
}
}

</script>

[/html]

Explanation:

In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code

[php]

<?php
$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
{
echo '<tr><td>'.$row['Name'].'</td></tr>';
}
}

mysql_close($con);
?>

[/php]

Conclusion:
Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:


download


download

Jul 7, 2011

Wordpress Search URL Rewrite

Have you ever considered your wp-site search URL?

http://yoursite.com/?s=searchterm

Also after setting the custom permalink structure, the only URL which is not effected is the search URL, it still remains the same.
OK, now goto your site, and after your root URL, just type this search/term

http://yoursite.com/search/term

Woila!!!! you'll find that the search worked, just that there is no URL rewrite rule written for this.
So to make it done, just add the following function to your themes functions.php file

[php]
function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');=
[/php]


This function will now rewrite every search results URL. Which will something look like this:-

http://yoursite.com/search/term

I have just implemented this technique on Webs Tutorial.

Jun 28, 2011

Configure VPS | Install LAMP on Centos VPS Part 1

Few days before when I had a VPS and needed to install wordpress, I found it very difficult because very few resources were available on google
So I am here now with my new post, On HOW TO INSTALL LAMP ON CENTOS
First buy an unmanaged VPS, and get ssh access
Then install Putty software in your computer, and start it
Then Follow the further steps
Start Putty software and then enter your IP for eg. 255.255.255.254
it will ask for username
generally its root and then enter the password
after that start typing the following code
IMPORTANT: IF YOU ARE NOT FAMILIAR WITH SSH COMMAND THEN BE CAREFUL. JUST COPY PASTE THE CODES.
First we will install yum

[php]
yum install -y yum-priorities

[/php]


After this we need to download updated repositories for php and mysql

[php]
wget http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm

wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm

[/php]


Then we will extract that by following command
code:

[php]

rpm -Uvh epel-release-5-4.noarch.rpm

rpm -Uvh remi-release-5.rpm

[/php]

After This we give priorities to repo and exclude php mysql and phpmyadmin from repository
code:

[php]

vi /etc/yum.repos.d/CentOS-Base.repo
[/php]

After this a file will be opened, press I from the keyboard to edit it, and after editing press esc button and type :x to save it
code:

[php]

priority=1
exclude=*php* *mysql* *phpmyadmin*

[/php]

Copy paste this above code five times before the following lines

[php]
#released updates
#packages used/produced in the build but not released
#additional packages that may be useful
#additional packages that extend functionality of existing packages
Copy paste the next lines before this line #contrib - packages by Centos Users

[/php]



[php]
priority=2
exclude=*php* *mysql* *phpmyadmin*

[/php]

Just one line above priority=2 their will be a line enabled=0 just make that to 1
After this press esc and type :x to save the file
Now same thing for epel and remi repository


[php]

vi /etc/yum.repos.d/epel.repo
[/php]

Just Above this line [epel-debuginfo] insert this code(inserting and saving is been explained on top)
Code:

[php]

priority=3

[/php]

Now after saving that, we will now edit the same code with just different filename
Code:

[php]

vi /etc/yum.repos.d/remi.repo

[/php]

And now in this, just above [remi-test] line, change the value of enable=0 to 1
and paste this code exactly above the [remi-test] line
Code:

[php]

priority=3

[/php]

Save it and now we will install apache web server,


[php]
yum install -y httpd

[/php]

After this we will install php,

[php]

yum install php

[/php]

During the installation it will prompt you for importing GPG key for the new repositories, just type y and press enter, this will be come for two times
Now we will start the Apache server
Code:

[php]

/etc/init.d/httpd start

[/php]

Just to test our Apache and php, we will create a phpinfo file


[php]

vi /var/www/html/info.php

[/php]

A new file will be created, insert this code into it, and then save it



[php]

<?
phpinfo();
?>

[/php]

Now in your browser, enter this URL, http://your IP or localhost/info.php
Now a PHP INFO file should open, where it will display php and servers information
if not then restart the apache server,
To restart the server,



[php]

/etc/init.d/httpd restart

[/php]

Now we will install MySql



[php]

yum install -y mysql-server mysql php-mysql

[/php]

Now the next code is used to configure Apache , to start MySql when server is rebooted.


[php]
chkconfig httpd on
chkconfig mysqld on

[/php]

Fire up MySql Server


[php]

/etc/init.d/mysqld start

[/php]

Now we will set the root password of mysql

Code:

[php]

mysql -u root password password
[/php]

Here the second password is the actual root password, you can change it with your's own.

Now its time to do last job, thats installing phpmyadmin



[php]

yum install -y phpmyadmin
[/php]

Now we have to edit phpMyAdmin config file to avoid the Forbidden Access Error



[php]

vi /etc/httpd/conf.d/phpMyAdmin.conf

[/php]

Search for a line,

[php]

deny from all# deny from all

[/php]

Comment the above line just by inserting # before the line, so after that, it should look like the following,

# deny from all

Save it and restart the Apache server

Code:

[php]

/etc/init.d/httpd restart

[/php]

Done
Now goto the browser and type this URL
http://IP or localhost/phpmyadmin
Now the page will appear, just enter username as root and password as password

Check my next post, Part-2, on how to transfer a wordpress site from existing hosting to your newly configured VPS
Feel free to give suggestions.