PHP Tips & Tutorials

How to check if a MySQL database connection is successful in PHP?

If you have mysqli extension installed with PHP and you use it to perform database operations, after you have tried to connect to MySQL by:

$conn = new mysqli('localhost', 'db_user', 'db_pwd', 'db_name');

You can then check if the connection is successful by:

if ($conn -> connect_errno) {
  // failure
} else {
  // success

That’s because connect_errno contains the error number of the last query. If there’s no error, it’s 0 by default. If an error occurred in the last query, it’s a natural number greater than zero. There you go with the conditional check of whether the PHP database connection is successful.

However if you are using the legacy mysql extension to connect to MySQL databases:

$conn = mysql_connect('localhost', 'db_user', 'db_pwd');

It’s even simpler. The returned value of mysql_connect() function will be FALSE should the connection fail. Therefore, you can check if the connection is successful by:

if ($conn = mysql_connect('localhost', 'db_user', 'db_pwd')) {
  // success
} else {
  // failure
SQL / MySQL Tips and Tutorials

MySQL: Check if a table exists

When I was creating an installation script, I needed to check if a table exists to make sure the installation had not been performed yet. How did I do that?

I use this simple query to get whether a table exists in the specified database:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'db_name'
AND table_name = 'table_name'

Just fill in the ‘db_name’ as well as ‘table_name’. If this query returns 1 row, the table db_name.table_name does exist, otherwise it does not.

Kavoir & Whatever

My online income report – June, 2010

Edit: Forgot all the website advertising revenues other than AdSense. Added it.

So I thought I should start writing things that are more personal and interesting. I ended up with this crazy idea – posting about my online income. People always want to know how much people make online, and more importantly, how they have made the money online.

Listed below are my primary sources of income from last month, June, 2010.

  1. Google AdSense – $740.91
  2. Sales of my own products – $960.75
  3. Amazon Associate Program – $54.67
  4. Other affiliate / partner programs – $932.44
  5. Website advertising revenues other than AdSense (such as the buy sell ads on - Roughly $250

And the total amount of earnings I have made online from last month is about $2938. It’s not bad considering I spend like only 3 hours a day and 5 days a week working from home on my PC to get all this. The above earnings didn’t include my freelance projects which I used to rely on heavily for the primary source of income. I don’t quite like them because it’s not passive so I’m giving up on them. Unless it’s a very interesting project that I feel compelled to work on, I’d not do it for less than 5 figures.

If you would like to know how you can do this yourself, making 4 figures monthly, feel free to comment below and let me know. I will help as much as I can. Otherwise, what can you suggest as an interesting topic for

JavaScript Tips & Tutorials

How to include a JavaScript file inside a JavaScript file?

This is a pretty odd question to ask in the first place if you have been using JavaScript for a while. JavaScript files are called from HTML web pages who need them to manipulate the HTML elements so that the users have extraordinary interactive experience. You can’t include a JavaScript file inside another JavaScript file like you can with PHP files, but you can only include JS files from HTML files.

If you need something that’s in a JavaScript file such as a predefined function, just include the file before wherever you are using the function and it should be fine. For example, you are calling A.js from a HTML file:

<script type="text/javascript" src="A.js"></script>

There is a rather sophisticated function in B.js that A.js relies on. You are wondering how to include B.js in A.js so A.js works properly. No you can’t. The answer is not to include B.js in A.js but include B.js in the HTML file before it includes A.js.

<script type="text/javascript" src="B.js"></script>
<script type="text/javascript" src="A.js"></script>

Now all the code in A.js should work fine. This is because all HTML code are read, parsed and executed in basic sequence from top to bottom. It’s the same with JavaScript code. When you need something from another JavaScript file and want to use it on the web page, just include it in the HTML web page. You can’t include a JavaScript file in a JavaScript file.

JavaScript Tips & Tutorials

JavaScript: How to set focus to form elements?

Normally, when users click on any label tag with the cursor, the corresponding input field will be focused ready for input or selection. Therefore, you can always achieve the focus effect by this native function of HTML’s. Otherwise, you’d need a small dime of JavaScript to set focus to any form element on the fly upon a certain event:

// FormName is the name value of the form.
// FieldName is the name value of the field
// to be focused.

Or by element ID:

// FieldId is the id value of the field
// element to be focused.

There you go, the tiny focus() function is what we all need.

JavaScript Tips & Tutorials

JavaScript: How to get the URL of the current web page?

To get the URL address of the current page with JavaScript, simply return the value of window.location.href:


Which is the same with:


There’s much more you can do with the JavaScript Location Object such as redirecting to another URL.

PHP Tips & Tutorials

How to execute / run PHP scripts in the background?

If the website is run on a Linux server, everything that can be run from the web (i.e., from the browser address bar) can be run from the Linux console. That is if you have the SSH access which most hosts provide. Connect to your hosting server via SSH by putty and you will have the ultimate control over your box. For example, you can execute a PHP script called routine.php via SSH by:

/usr/bin/php5 routine.php #routine.php is in the current working directory

Depending on your distro and PHP installation options, the command line interpreter (in this case, /usr/bin/php5) may vary in location.

You can add this line to a crontab job and it the PHP script routine.php will be executed by your designated intervals or at any certain time, automatically.

Other than calling PHP scripts from Linux console via SSH, you can also call to execute PHP code in another script file from the current PHP file. For instance, in A.php:

exec('/usr/bin/php5 B.php');

As it obviously suggests, this line will run the Linux command ‘/usr/bin/php5 B.php’ and you can put stuff in B.php that will be taken care of when this line in A.php is executed.

There are a variety of different PHP functions that perform essentially the same task, running system commands: exec, shell_exec, system and passthru.

PHP Tips & Tutorials

PHP: Delay Function that Halt Code Execution Temporarily and Then Resume It

Sometimes you need to temporarily halt the code execution of your PHP script for certain seconds and then automatically resume it. For example, some mail delivery servers have the restriction that you have to wait a certain interval such as 12 seconds before sending another email.

You can tell your PHP script to stop for 12 seconds before continuing down with the rest of the code by sleep() function:

sleep(12); // freeze PHP execution for 12 seconds before going ahead

That’s it. When it is executed to this line, PHP will freeze for 12 seconds, doing nothing, and then go on with the line immediately after this line.

PayPal & Ecommerce

Way to go PayPal! – Fraudulent Chargeback Successfully Resolved in Merchant’s Favor

I made a sale months ago when someone purchased a few website scripts for over $1,500. A few days after the transaction he fired a chargeback dispute. I thought, well ok, I’m puked. I almost gave in. But then I thought I couldn’t let him win this easily.

So I provided everything I can with regards to the dispute case in the PayPal resolution center, including transaction logs, email communications and several screenshots of proof that he had received the digital goods. A few days later, the funds are transferred away anyway. I lost.

This morning, however, PayPal sent me an email, over 100 days later:

Hello Kavoir,

We are pleased to inform you that we have successfully disputed chargeback
case #PP-xxx-xxx-xxx-xxx.  The buyer’s card issuer has decided in your
favor and within seven days you will receive reimbursement for $xxxx.xx USD.

This is truly a surprise and a good one. You can imagine the look I had when I read the message. To make sure, I logged into my PayPal account and saw the funds right reimbursed.

How awesome is that.

JavaScript Tips & Tutorials PHP Tips & Tutorials

PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?

This is a rather common problem for novice web developers. While it may seem at first glance that it’s easy for PHP and JavaScript to communicate with each other, but they actually cannot interact with each other directly. They are very different technologies built for distinct purposes.

How to transfer or pass variable values from PHP to JavaScript?

To pass variables or values from PHP to JavaScript, just write the PHP code to generate the client side JavaScript code as you would with HTML code:

var jsVar = "<?php echo $phpVar ?>";

To embed PHP code in *.js files you have to first make the server to parse JavaScript .js files for any PHP code so that they will be executed. After that, you can create classes or call to functions or do whatever that is allowed in PHP in the .js files just as you can with .php files.

How to transfer or pass variable values from JavaScript to PHP?

Simply put, you have no other way to let some PHP script know any variable value than to send a request to it. So, you will use JavaScript to send a request to the PHP script by a GET or POST request that bears the variable value.

You can trigger a redirection to the PHP script and pass the values via URL:

var age = 24;
document.location = '' + age;

Or you can perform an XMLHttpRequest request by GET or by POST.