Directory

CodeIgniter

PHP and MySQL

Javascript and Jquery

CSS

HTML 5

Programming Practices

.Net Framework

Ruby on Rails

Java

PHP Frameworks

Troubleshooting

Software

Hardware

CMS

Security

Theme Customization

Resources

Anime

Miscellaneous

PSP Games

How to create a simple CRUD application using Mongo db and php

In this tutorial I’m going to show you how to create a simple crud application using Mongo DB and php. If you want to know how to install Mongo DB, visit the link below:

How to install Mongo DB on php

Configuration File
First you’re going to need to create a database configuration file which connects to your Mongo DB. Just like in MySQL, we also make use of a configuration file that we will just include on the files where we are going to need to query the database. This is to save time and avoid repeating of code.

<?php
$conn = new Mongo();
$db = $conn->test;
$collection = $db->people;
?>

Let me break down the code for you:

  • $conn = new Mongo()  – this initializes the Mongo DB class which contains all the methods which you can use to manipulate data in mongo DB through php.
  • $db = $conn->test – the default name for the Mongo database is test. This code is used for connecting to the database.
  • $collection = $db->people – collections are similar to tables in mysql. This code is used to reference the collection called people. But not unlike in mysql where you have to create the table first from the mysql console or a third-party database manager like phpmyadmin or heidi sql.
    In mongo DB you can basically use any collection name that you want, without having to create it.

 

Create
Now on to the exciting part, first let’s try inserting data into the database. Go ahead and create a form which the user can interact with. Don’t forget to include the database configuration file.

<?php
require_once('mongo_config.php');
?>
<form action="create_users.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name">
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes">
</p>
<p>
<input type="submit" value="Save">
</p>
</form>

Next, create the function that will check if all the values has been filled out. What the function does is to loop through the array of values that is being passed through it. But we have check first if the value is actually an array so that we don’t get any errors. If one or more values are empty, the function returns 1. If not then it returns its original value which is 0. We can then use that returned value to make a decision whether to continue the insertion of the record or not.

<?php
function check_empty($ar){
    $empty = 0;
    if(is_array($ar)){
        foreach($ar as $v){
            if(empty($v)){
              $empty = 1;
            }
        }
    }
return $empty;
}	
?>

Next is the code for inserting records.

<?php
if(!empty($_POST)){
	$people = $collection->find();
	$people_count = $people->count();
	
	$empty = check_empty($_POST);
	if($empty != 1){
		$id = $people_count + 1;
		$name = $_POST['name'];
		$age = $_POST['age'];
		$likes = $_POST['likes'];
		
		$person = array('id'=>$id, 'name'=>$name, 'age'=>$age, 'likes'=>$likes);
		
		$collection->insert($person);
		echo $name . ' is registered!';
	}else{
		echo 'Please fill out all the fields!';
	}
}
?>

  • if(!empty($_POST)) – First we checked if the $_POST superglobal is empty. This is the first step, because we don’t want to be executing all the code when the user access the page.
  • $people = $collection->find() – Call the find() method, this returns an array of all the records in the collection. Which if you still remember, the people collection as we have declared in the configuration file.
  • $people_count = $people->count() – Call the count() method, as the names suggests it just counts how many records are in the people collection. We then store that value into the $people_count variable.
  • $empty = check_empty($_POST) – Call the check_empty() function that we created earlier, and use the $_POST superglobal as an argument.

Next is just the assigning of the values from the submitted form to a php variable. Then place all those values in an aarray called $person. We then use the insert() function and supply the $person array as an argument. Nice and simple.

 

Read
Fetching the data is also dead simple. We only have to call the find() method and loop through it. Of course, we also need to use the count() method to check if there are actually records to fetch. We ditch the whole thing if the $people_count stores the value of 0.

<?php
require_once('mongo_config.php');


$people = $collection->find();
$people_count = $people->count();

echo $people_count . ' records found<br/>';

if($people_count > 0){
?>

<table border="1">
<thead>
	<tr>
		<th>ID</th>
		<th>Name</th>
		<th>Age</th>
		<th>Likes</th>
	</tr>
</thead>
<tbody>
	<?php foreach($people as $v){ ?>
	<tr>
		<td><a href="update_user.php?name=<?php echo $v['name']; ?>"><?php echo $v['id']; ?></a></td>
		<td><?php echo $v['name']; ?></td>
		<td><?php echo $v['age']; ?></td>
		<td><?php echo $v['likes']; ?></td>
	</tr>
	<?php } ?>
</tbody>
</table>
<?php } ?>

 

Update
Updating is also dead simple. We just make use of the findOne() function to fetch a single record from the collection. The argument that it will need is an array which contains the field name and its value. We already supplied the value in the link for updating. Were going to make use of the name as the query string(since the id that I supplied doesn’t work for me, grr. I guess the problem is the name id itself, you’ll have to use a different name if you want to make use of a custom id to reference the records).

<a href="update_user.php?name=<?php echo $v['name']; ?>">

Here’s the code(sorry for the poor indentation):

<?php
require_once('mongo_config.php');

if(!empty($_GET['name'])){
$name = $_GET['name'];
$query = array('name'=>$name);

$person = $collection->findOne($query);
$name = $person['name'];
$age =  $person['age'];
$likes =  $person['likes'];

?>
<form action="update_user.php" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>" readonly>
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age" value="<?php echo $age; ?>">
</p>
<p>
<label for="likes">Likes:</label>
<input type="text" name="likes" value="<?php echo $likes; ?>">
</p>
<p>
<input type="submit" value="Update">
</p>
</form>
<?php } ?>

Remember that $_GET is not a secure way of passing variables from one page to another. This is just for examples, don’t use it on any project(although personal projects may do, or any projects that will not be used by other people).

To update the record. First we check if any fields is empty, we don’t actually do a thing if one of the fields are empty. Assign the $_POST values to a variable. Call the findOne() method, using the name as the query string. Assign the new values, then commit to the database using the save() function.

<?php 
if(!empty($_POST)){
	$empty = check_empty($_POST);
	if($empty != 1){
	
	$name = $_POST['name'];
	$age = $_POST['age'];
	$likes = $_POST['likes'];
	
	$query = array('name'=>$name);
	$person = $collection->findOne($query);
	
	$person['age'] = $age;
	$person['likes'] = $likes;
	$collection->save($person);
	
	echo 'Update Successful!';
	}
}
?>

Note: we used the check_empty() function again. You might want to copy it on the file if you don’t want to get WHAT FUNCTION ARE YOU TALKING ABOUT errors.

 

Conclusion
That’s it for this tutorial. We have just touch the surface of using Mongo DB and php to create database oriented applications.
Yes I’ve said CRUD application, but I’m going to leave record deletion as your assignment. You just have to make use of the findOne() and the remove() function. Thanks for reading!

How to install Mongo db on php

In this tutorial I’m going to show you how you can install the  Mongo DB extension on php. But first, let me give you a simple introduction on what Mongo DB is. Mongo DB is a NO SQL database, which means Not Only Standard Query Language. Here’s a list of NO SQL databases:

http://nosql-database.org/

So what’s the advantage of Mongo DB over MySQL or other databases which uses SQL? Here’s the introduction of Mongo DB:

http://www.mongodb.org/display/DOCS/Introduction

And here’s a summary in case you’re feeling lazy today:

  • Document-oriented
  • High Performance
  • High availability
  • Easy Scalability
  • Rich query Language

Well, I’m not that expert at explaining things. And the main purpose of this article is to show you how to install Mongo DB, so I guess a simple outline will do. And yeah, you’re lazy today so you won’t really be reading this part and have gone ahead with the installation.

 

Requirements

 

Installation

First, you’ll have to go to the download page of the Mongo DB. And you’ll see a highly confusing table, you’ll really have to examine it carefully in order to download the right one. Basically you’ll want a production release that is for Windows 32-bit operating system. It says Windows 32-bit, but I don’t really know if it works on Windows 95 or the first version of Windows. But if you are on Windows 7 just like me, the it will probably work for you.

image

Next, download the mongo DB extension for php. You can use this link to download the php extension if you didn’t catch the link above. But first, you need to make sure that we have the same php version and compiler. If not then you can use this link, a collection of mongo DB extensions for php 5.3.5. And if you don’t know how to get the information below, just create a new php file and type phpinfo(), save it then access the file on your browser.

image

Next, extract the mongo DB archive file. Then go to the bin folder. What you’ll see is a bunch of executable files, but you only have to execute 2 of them. Here’s the order of execution:

  1. mongod
  2. mongo

You can go ahead and try some commands like:

db.people.save({name: 'ash'});

It’s the equivalent of the insert command in sql.

If you want to verify that it is actually stored in the database, you can try out this command:

db.people.findOne({name: 'ash'});

Yup!, that’s the equivalent of the select statement in sql.

Ok, enough with that. You can go give yourself a jumpstart by taking up the tutorial in the mongo DB site, just click on the big TRY IT OUT LINK to get started.

Next, paste the mongo DB extension to the ext folder in php. The path to my ext folder looks something like the one below. You can make use of it as a basis.

D:wampbinphpphp5.3.5ext

Next, you have to insert this line on the php.ini file. Of course, you don’t paste it on just anywhere else. You have to paste it where the other extensions are

extension=php_mongo.dll

I have placed mine as the first extension on the list, the one’s with the semi-colon at the beginning are disabled. You can also enable and disable existing extensions from the wampserver tray icon. But because the mongo DB extension doesn’t yet exist, we needed to manually place it on the php.ini file:

image

After that, save the changes to you php.ini file and restart all services from the wampserver tray icon.

To test if you can already make use of Mongo DB in php, just create a new php file and paste this line:

$conn = new Mongo();

If you don’t get any error, then All Izz Well as Phunsuk Wangdu said(that’s from the movie called 3 idiots, definitely worth watching, very funny and inspiring).

But if you get any errors, here’s what you need to do:

  • Make sure that mongo.exe and mongod.exe are running, you can go check it out from the Windows Task Manager.
  • Make sure that you have the right mongo DB php extension and that it is enabled.

 

Conclusion
That’s it for this tutorial! Mongo DB is a good My SQL alternative for small php projects. Next time, were going to make a simple CRUD application using php and mongo DB.

Things to do before you present your php project

In this article I’m going to share to you some of the things that you need to check before you present your php project. Some of these things often get left out and actually stays unpatched. Yup! I’m talking about errors here. Errors which only shows up accidentally. Errors which can only appear by letting an idiot or a monkey use your system. Yes, systems are made for humans but sometimes you need to act like a monkey in order to uncover the errors.

 

String Sanitization
Sanitizing your string is number one on this list folks. Most of the web applications today uses databases to store and retrieve data. And to store and retrieve data, we use SQL or the Standard Query Language. And SQL only allows certain keywords, you actually get an error if you don’t comply with the syntax just like with any programming language.
So where does string sanitization enter from here? Here’s an example query to let you understand where will we need string sanitization, try to run it if you don’t know the output yet:

SELECT * FROM def_transactions WHERE transactionID='''

That’s just the query, in php it looks like this:

<?php
$transaction_id = $_POST['trans_id'];
$db->query("SELECT * FROM def_transactions WHERE transactionID='$transaction_id');
?>

You can conclude now that the same SQL error will pop out if someone inputs a single quote on the transaction id field. Go ahead and try it.

So how do we sanitize the string?The simplest way to sanitize a string is already built-in to php. The mysql_real_escape_string() function. You use it this way:

<?php
$transaction_id = mysql_real_escape_string($_POST['trans_id']);
$db->query("SELECT * FROM def_transactions WHERE transactionID='$transaction_id');
?>

The error won’t bother you again. What mysql_real_escape_string() does is to escape all the characters which are invalid in SQL. You might say that it’s an addslashes() on steroids.

 

Empty Results
Second on the list is empty results. Its crucial to check if the query that you’re trying to call actually returns any result set. You’re asking for trouble if you don’t perform checks. Consider the following example:

<?php

$name = $_POST[‘name’]; $results = $db->get_results("SELECT * FROM tbl_people WHERE name LIKE ‘%$name%’"); foreach($results as $r){ echo $r->name.'<br/>'; } ?>

So what’s wrong with the code above? Aside from the fact that we didn’t perform sanitization. You might also noticed that we’ve gone ahead and loop through the results without even checking if there are any results at all. The code returns an error which tells you that the argument passed to the foreach loop is invalid. To fix the code we change it to the one below.

<?php$name = $_POST[‘name’];
$results = $db->get_results("SELECT * FROM tbl_people WHERE name LIKE ‘%$name%’");
    if(!empty($results)){
        foreach($results as $r){
            echo $r->name.'<br/>';
        }
    }
?>

 

Thorough Checking
Before you present any application you must thoroughly check that its working fine and that errors doesn’t show up here and there. But test your application in such a way that errors will actually show up. Here’s how:

  • Input all sorts of crazy stuff, symbols, and other unnecessary characters on the text fields.
  • Test all the possibilities, not just one. For example, if you have a function that returns either true or false based on the value of the argument that is passed to it, then test it in such a way that you see true and false. Don’t conclude that its working 100% if you’ve only seen one side of the coin.
  • Examine your application. If you see something that you think isn’t user friendly, something that you think might cause some errors in the future, or a text field which shouldn’t take a specific data type. Then take note of it and change it if you have enough time. Don’t push lots of changes overnight if you think you can’t make it.
  • Make sure that the flow of the program is correct.
  • Let others use your application. And ask them for suggestions or if they’ve seen any errors.

 

Turn Off Error Reporting
This might be your last option. Turning off error reporting is not advisable if you’re still in the process of testing your application. But if you don’t want anyone to be seeing errors while your presenting your application this is your best bet. To turn off error reporting just uncomment the production values just like the one below, you can use the find tool to quickly jump to the lines below:

; display_errors
;   Default Value: On
;   Development Value: On
    Production Value: Off

; display_startup_errors
;   Default Value: Off
;   Development Value: On
    Production Value: Off

; error_reporting
;   Default Value: E_ALL & ~E_NOTICE
;   Development Value: E_ALL | E_STRICT
    Production Value: E_ALL & ~E_DEPRECATED

; html_errors
;   Default Value: On
;   Development Value: On
    Production value: Off

Here’s a sample code that will issue an error if the default values for error reporting are being used:

<?php
echo $a;
?>

Here’s what you usually get if you run the code above:
image

And here’s what you get if you uncomment the production values for error reporting:

image

Awesome, but I only recommend this one as  a last resort. Be careful to comment out the production values after your presentation as this might give you the illusion that there is nothing wrong with your program.

 

Conclusion
I guess that’s it! You’ve learned some of the things that you should do before presenting your php application. These tips might also apply to other programming project not just in php. I hope you enjoyed reading!

How to solve router disconnection problems

Yep! I know why you’re here, you’re  router always disconnects when you’re doing something really important. Like downloading anime or streaming a youtube video.
In this quick tutorial I’m going to show you how to solve the problem.

 

Reboot the router
You can always reboot the router if it suddenly disconnects. To do that, just access your router from the browser by going to http://192.168.1.1/  or http://192.168.0.1
Its not always those two, a little googling will help if you cannot access anything from the addresses that I gave you.
To reboot your router, just go to system tools then select reboot. Click the reboot button if there is any. If the reboot is successful, you’ll be once again connected to the rest of the world.

 

Reboot the modem
If the first one didn’t do the trick. Then maybe the router isn’t the problem. Just try to reboot the modem if the problem still persist. To do that just open up the cmd. And type the following to release your current ip address:

ipconfig/release

Then renew it:

ipconfig/renew

 

Remove the plug
If all else fails, perhaps its now time to remove the plug for about 3 minutes then put it back again. In short a physical reboot.

 

Conclusion
Ok that’s it. The solutions that I have shared to you are not long-term solutions, the problem might still persist in the future.

Programming practices

When developing an application, especially a huge one that may take several months to finish. We tend to develop some practices and techniques that we use all throughout the development process. Some are bad, some are good. In this article, I’m going to share to you the practices that I have developed so far. Its up to you to classify if it’s a good or a bad practice.

Code Comments
Using comments to indicate where a block ends.

if(){
    do(){

   }//end of do while
}//end of if

 

Table Truncation
Writing a separate script for truncating the tables that are affected by the current program that I’m testing. That is to easily work on a clean slate if the program didn’t work correctly. Which in turn messes up the table. What I do is to open the file in the browser, then refresh the page if anything goes wrong to start with a clean table.

 

Fresh Air
Breathing air from the outside environment is very effective in solving a programming problem. If you’re stuck with a problem for more than an hour already and you believe that you could have done it in just 5 minutes, then its better to get out of chair, go outside and breath some fresh air. 80% of the time you will come up with a solution, believe me.

 

 Firebug + console.log()
Using debugging tools like Firebug when developing applications to reduce the time spent on debugging. And using console.log to output things on the console. Perhaps most of us uses the alert() function. That’s very time consuming especially if you have to output lots, you also have to click on the OK button lots of times. And there are also other things that you cannot output using the alert() function.

 

Testing Folder
Also called the testing area. This is where I put files which are intended for testing code. If I’m not sure with the code that I’m writing. Or if I want to test out some other things which are not directly connected to the application that I’m working on, I put them all to the testing folder. To isolate things and to give myself the feeling that I’m working in a smaller file, with lesser code in it. Its not really easy to work on a file that has already lots of code in it.

 

Taking Notes
Taking down notes, making sketches in a scrap paper if you can’t directly write the code on your computer. It’s also a good place to write an algorithm. One of the most useful apps for note taking is Evernote. I definitely recommend it.

 

Breaking Down
Breaking down the procedural code into their respective functions. Makes it easier to copy those code into a larger file later on. But before you can break down something, make sure that you have already the working procedural code where you will base things.

function get_monthsDelayed(){

}

function get_surcharge(){


}

 

Database Backup
Always see to it that you are backing up the database that your application is using. Especially if you are the kind of person who is making modifications in the database structure while creating the application. Its always wise to have backups of the previous version of your database.

 

Code Snippets
Storing codes that you often used in a program like Snippley to save time. Retyping the same code over and over again isn’t time efficient, especially if you are to meet deadlines.

Naming Conventions
As we type more code, develop more applications. We also tend to come up with our own naming conventions. For naming files, databases, tables, fields, classes, functions, and variables. Just be sure that the names that you give to each of those are comprehensive. You can check out this post from stackoverflow if you want to learn the best practices for naming conventions:

http://stackoverflow.com/questions/332831/best-practices-for-naming-conventions

Just make sure that you maintain the naming convention of your choice throughout a project. Be consistent.

 

Folder Structure
When developing applications make sure that you properly organize different files. Here’s an example of a folder structure:

image

Here’s a summary of the folder structure that I’m using:

  • First, make individual folders for each file types. That would be .php, .css, .js
  • If using an external library, frameworks or javascript plugins place them on a separate folder. To distinguish which file belongs to what library.
  • If the application comprises of modules, also separate the files that belong to each module. That is by creating a separate folder for each module. Common files for each module can be placed outside of the folder.
  • If using files which processes data in the background, also create a separate folder for them. You may want to further group those files using folders or by just using a naming convention to distinguish which module uses which file.

 


Screenshots
Taking screenshots  to compare outputs. When saving data into the database and you want to verify that what you have inputted is actually going to the right place, then you can use tools like Snipping Tool. A built-in Screenshot tool for Windows 7.

 

Google
We don’t know everything. No matter how good you are there will always be a time that you’ll need to consult Google. If it is a specific code that you’re looking for, its always nice to study it first. Study what the code does, and how it work. Don’t just copy and paste. You won’t learn anything from that.

 

Give yourself a break
No matter how passionate you are there are always times when you feel like you have lost all energy to continue working on your project. That’s why its also important to have a break. Watch some movies, listen to relaxing music, play some games, or watch anime. Once you come back,  you’ll feel that you’ve been energized and you’ll actually want to work on your project as soon as possible.

 

Conclusion
There you go. As I’ve said earlier, its up for you to decide if what I’ve tackled here are good or bad practices. And as I have said in the disclaimer, I’m not in any way expert in this field. I’m still just learning just like the rest of us.
Feel free to use the comments section if you have anything to share or to ask. Thanks!