jQuery UI Dialog Example with Source Code Downloads

Dialog boxes, modals, confirm boxes can also be done with awesomeness in jQuery UI.

In this post we are going to take a look at the three jQuery UI dialog code examples I commonly use in my projects.

Live demos and code download button links were also provided below. Keep on reading!

jquery ui dialog example

Our jQuery, jQuery UI and jQuery UI theme are hosted by Google. You can choose your jQuery UI theme here.

jQuery UI Basic Modal

I love modals, or a "modal window" or "modal dialog", it is a child window that pops up in your application that requires a user interaction. It can display information, gives you choices or even contain an HTML form!

In jQuery UI, when you set modal: true parameter, it will be able to dim the background of your page when showing the dialog. If it is set to false, the background will remain as is.

This is useful when a client (like mine) did not like dimming the background. But I like dimming the background when showing a dialog, so in our code below, we'll set the modal to true.

basic-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Modal Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -you can set the dialog title via the 'title' tag 
-->
<div id="basicModal" title="A message from codeofaninja.com">
    Thank you for visiting codeofaninja.com!
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* -select the div you want to be a dialog modal, in our case it is 'basicModal'
       -you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        height: 300,
        width: 400
    });
     
});
</script>
 
</body>
</html>

jQuery UI Confirm Dialog

Instead of the old JavaScript confirm dialog box, I use jQuery UI. This is for a better user interface and to control the number of buttons and their labels, instead of just "ok" and "cancel".

confirm-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Confirm Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show confirm dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -we did not set the dialog 'title' here, we set it in the js parameter
-->
<div id="basicModal">
    Go to codeofaninja.com?
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* select the div you want to be a dialog, in our case it is 'basicModal'
    you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        title: "Are you sure?",
        buttons: {
            "YES": function() {
                window.open("https://codeofaninja.com/", '_blank');
            },
            "NO": function() {
                $( this ).dialog( "close" );
            }
        }
    });
     
});
</script>
 
</body>
</html>

jQuery UI Load Content from URL

URL to be loaded must be in the same domain or subdomain name. If you really want to load from different domain, use iframes, example code here.

In this example, we will use sample_page.php as the file of URL to be loaded, it has the following contents:

<?php
echo "Here's the sample page loaded.<br /><br />";
echo "Only a page from the same domain/subdomain can be loaded using this technique.<br /><br />";
echo "If you really want to load a page from another domain/subdomain, use an iframe.<br /><br />";
echo "<a href='http://stackoverflow.com/a/14570255/903298' target='_blank'>Example code here</a>";
?>

Save the loaded URL content

Here's is the default behaviour of the jQuery UI dialog, it appends the URL content to the HTML body.

load-url-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
 -->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    console.log("url: " + url);
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL contents will be appended in the body of your HTML document, see the screenshot below, I used Google Chrome's inspect element to view this live source code of the current page.

jquery ui dialog not destroyed or removed

LIVE DEMO

Destroy or remove the loaded URL content

By default, the jQuery UI append the URL contents in your HTML body, if you want to prevent it, we can we add the close parameter on the dialog and use the jQuery remove() method.

load-url-destroy-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
         
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
-->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450,
                close: function(){
                     tag.dialog('destroy').remove()
                }
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL content did not append in the HTML body, see the screenshot of the live source code below.

jquery ui dialog was destroyed and removed

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12411" text="Download Now" style="button" color="green"]

If you think of any other jQuery UI dialog example, please drop it in the comments section below, we'll try our best to add it in this post. Thanks!

Optimize Image for Web Using Photoshop and Thoughts on Faster Web Pages

This post is supposed to be a quick-tip on how you can optimize your images for web pages. But it feels like I also want to give some thoughts about website speed. There are many websites saying that your images must be optimized for the web, that should be updated and say, "your images must be optimized for web and mobile devices" in which the amazing Adobe Photoshop can help us with.

But before the tutorial and showing you the amazing results, I just want to give some thoughts on faster web pages. Optimizing your images can benefit, youyour users and search engines such as Google.

WEBSITE OWNER

I love fast loading web pages. Over a month ago, Alexa says this website's load time is around 4 to 6 seconds. That's horrible. So I decided to make this website load faster. Here are some of the things I've done to make it possible:

  1. I removed Infolinks ads to achieve speed in exchange for few bucks.
  2. I removed my Twitter and Google plus follow buttons.
  3. I removed Facebook like box, it loads images of Facebook users which is slow. The one you're seeing on the right sidebar is just an optimized image.
  4. I removed some jQuery plugins such as the "Recent Posts" plugin, the one you're seeing in the right sidebar is just a hard coded HTML.
  5. I limited "Related Posts" plugin to show just 5 items. Each item is a callback that makes a slow page load.
  6. I removed my stylesheet hosted in Google drive. Google drive HTML/CSS hosting is really slow.
  7. In short, lessen your HTTP requests.

Now a page from this site loads around 1 to 2 seconds. They say that it should be 1.5 seconds or less. But for now, the current speed is just okay for me. I'm still looking for ways to improve it, it's just I don't have much time for that yet.

YOUR VISITORS

You readers or website visitors also love your website to be fast even though you won't hear them saying it to your face. Everyone loves instant nowadays, instant noodles, instant result, etc. The same with web pages, users wants to read, or should I say scan, your content and get what's in your brain in an instant. One way to do this is making your web pages load fast.

GOOGLE

What you and your users love, Google love. If your visitors like their experience to your site, they might share it or link back to it. And Google can see it, which can give your website a chance to rank higher in search results. Currently, around 80% of this site's traffic comes from Google. Thank you Google!

HOW TO OPTIMIZE AN IMAGE FOR WEB AND DEVICES USING PHOTOSHOP?

Easy. Watch the video I made for you below

THE RESULT.

I chose to have a 'high' quality image. So from 80 kilobytes, it becomes 14 kilobytes.Here's the 80 kilobytes version:

...and now here's the 14 kilobytes version.

As for my eyes, it makes almost no difference aside from it's file size which is more than 4x smaller compared to the original. You can download the two images above and view their properties. Or you can do the few easy steps on the video above to see for yourself.I think this is a nice start for making your web pages load faster, and as always, thanks for reading!

Fixed: Cannot send session cache limiter – headers already sent

Okay, so many of you guys still ask me about how to fix these warning messages in our Facebook scripts. Today I'm going to give you two possible fixes that you can do. By the way, here's the warning message we want to remove:

FIX IT BY ADDING A SESSION_START()

You can fix it by adding a session_start() on top of your PHP file, just right after your first line <?php tag. It looks like this:

FIX IT BY MOVING FACEBOOK INSTANCE

You can fix it by moving the Facebook class and instance code on top of your PHP file. It would look like this:

If none of them worked, you can read more here.

CakePHP Classes and Naming Conventions

Introduction

After installing CakePHP on your server, we now have to learn how to create CakePHP classes and its naming conventions. CakePHP uses Model–view–controller (MVC) software architecture which is really great. If you have no idea what MVC is, I think Wikipedia can give you a great overview. Also, you’re going to get the hang of it in this post.

Creating CakePHP MVC Files

In this example, we are going to use a database with “users” table and create code for the model, view and controller files. Let’s have fun!

Preparing the user’s table

Our users table will have only 5 fields which include: id, firstname, lastname, username, password.

CakePHP Classes and Naming Conventions

CakePHP requires a naming convention for our tables. It must be in plural form always. Like right now, we are going to have a table that stores data of users, it means that the name of our table must be “users“, NOT the singular “user” or something.

Creating a Model

A CakePHP model class manages your application data, rules of validity (for example, a username is required, or a password must consist of letters and numbers) and interactions (queries, etc.).

To create our CakePHP model, go to your app/Model directory, I found mine in C:wampwwwCakePhpProjappModel

On that directory, we will create a model file named “User.php

cakephp-model-naming-convention

CakePHP requires us to create a model file with singular name and with a .php extention, that’s how we come up with the filename “User.php”

If your model has more than one word, for example you have a table “user_permissions”, our Model filename will be camel cased and will look like “UserPermission.php”

Inside that file, we are going to have the Model basic code:

<?php
class User extends AppModel {
 
    public $name = 'User';
     
}
?>

Creating a View

A view in CakePHP is the output representation of data retrieved from the model and manipulated by the controller. It can be in the form of HTML, XML, JSON or even PDF!

To create our CakePHP view, we have to go to the app/View/ directory and create a directory called “Users”.

cakephp-view-directory

And then after creating the directory, we will now create the actual “view”, as an example, we are going to have “hello_user.ctp” and leave it as an empty file for now.

cakephp-ctp-file

CakePHP requires us to name a view with a .ctp extension. A view’s name is the same as its function in the controller. We’re going to see it later.

Creating a Controller

A CakePHP controller class is like the middleman between the Model and View. Controllers are used to manage the logic around a model, and it uses the View for that logic’s output.

To create a model, we are going to create a file named “UsersController.php”

cakephp-controller-file

We are going to have the controller’s basic code:

<?php
class UsersController extends Controller {
     
 
     
}
?>

Making MVC Work

Now that we have the required directory, files and basic code inside them, we are going to make this MVC thing work.

Playing with the controller

First, open your controller, add the following code:

public function hello_user(){
  
     $user = $this->User->findById(1);
     $this->set('user', $user);
 
 }

What just happened? As I said earlier, the view name (hello_user.ctp) will be the function name in the controller.

In this function, we tried to retrieve the record details of a user with an ID of 1.

$user = $this->User->findById(1);

To use the $user in the View, we have to use the $this->set() method. Yes, in CakePHP, passing variable values to view requires a $this->set() method.

Using the Model

For our model, we’ll leave it as is for now. It is used implicitly here in our example. How? Did you see the code $this->User in the controller? Yes, the “User” part of that code is the Model.

Viewing the View

Lastly, our view “hello_user.ctp” will present the data retrieved, we are going to have this code inside:

<?php
echo "Hello, " . $user['User']['firstname'] . "!";
?>

We retrieved the firstname like that. The $user variable gave us an array value, findById() method gave us this:

array(
    'User' => array(
        'password' => '*****',
        'id' => '1',
        'firstname' => 'Mike',
        'lastname' => 'Dalisay',
        'username' => 'ninjazhai'
    )
)

Run Code

Now here’s the exciting part, running our code. Go to your browser and type localhost/CakePhpProj/users/hello_user/

You should see something like.

cakephp-classes-name-convention-output

You might want to check out how to perform CRUD in CakePHP.

If you have any comment, suggestion or issues, just drop a comment below. :)

How To Use CakePHP Framework, A Getting Started Guide!

Introduction

Using CakePHP Framework is one of my most favorite things to do. This is the first PHP framework I worked with, and until now, I’m still delighted by it. Now it is time for me to share my knowledge in CakePHP web development.

I think you are here because you already know what CakePHP is, but for those who has no idea yet, and don’t want to read more on CakePHP.org, here’s a brief description: CakePHP makes building web applications simpler, faster and require less code.

I think there are really few blog posts out there with regards to beginner CakePHP tutorials. Most of them are also outdated. We will keep this CakePHP posts as updated as possible. So to the future reader of these posts, please drop something in the comment section below if you think there is something outdated!

We will start with the most basic thing to advanced. Hopefully I can finish this tutorial series in the shortest time possible.

Install CakePHP on Your Server

Below are few steps to make CakePHP alive in your hosting server, see sections 2.1 to 2.4 below.

By the way, if you’re a super beginner and using a windows PC (localhost), you can follow this tutorial first to set up your localhost: 3 Steps to Install WAMP on Windows

Download CakePH

So… what do you expect the first step will be? Of course, we will download the framework. Download the latest CakePHP version here: http://cakephp.org/

As of this writing, the version is CakePHP 2.3.6 stable.

Extract the ZIP file.

Put CakePHP on Your Hosting

I don’t know, but I think most of you guys are using a localhost (your PC or something). Okay, so I’ll assume you are all using your localhost. If you’re not, just give a comment so we can try help you with your issue.

After you download and extract the Framework files, you have to put it in your root directory. I’m using windows 8 and running with WAMP server, so in my case, my root directory is in:

C:\wamp\www\

Now after putting the extracted folder, my CakePHP directory is in:

C:\wamp\www\cakephp-cakephp-b81c198\

Of course, we want to change the dirty name “cakephp-cakephp-b81c198″ to our “project name”.

So we have to rename it and for this tutorial, we will name it “CakePhpProj”, awesome name right? If you don’t think so, you can choose the project name of your choice. Now we should have:

C:\wamp\www\CakePhpProj

Run CakePHP

Too early to run? You’re correct. This is just a test run. We just want to confirm if CakePHP can respond at this stage.

So to run CakePHP: Go to your browser > type “localhost/CakePhpProj“

You might see something beautiful like this:

using-cakephp-first-run

You might be disappointed or intimidated by now, but don’t worry, I’m at your side! Proceed to the next step below.

Configure CakePHP

Alright, so we’re going to address the issues on the previous screenshot, one at a time!

URL rewriting is not properly configured on your server.- Let’s start with this problem, this error is rare if you’re using a real hosting. But if you’re using localhost, here’s the fix:

1. On you notification area (lower right corner), click the WAMP icon.
2. Hover your mouse to the “Apache” folder
3. Hover your mouse to the “Apache modules” folder
4. Find and click “rewrite_module”, WAMP will automatically restart and check that apache module.

mod-rewrite-cakephp

After the fix, re-run our project on the browser, it should look like this now:

cakephp-fix-rewrite-mod

Please change the value of ‘Security.salt’ - To solve this, you have to to got the core.php file and just change the security salt string!

In my case, I have to open it in C:\wamp\www\CakePhpProj\app\Configcore.php

Find the word “salt” (Ctrl+F on your editor, I’m using notepad++)

You should see the line of code that looks like:

Configure::write(‘Security.salt’, ‘DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi’);

Change the value to something like:

Configure::write(‘Security.salt’, ‘nowthisismyawesomesaltthatnoonecaneverknowxfs2gu’);

Then re-run the browser:

cakephp-fixed-security-salt

Please change the value of ‘Security.cipherSeed’ - The solution is the same with 2.4.2, just change the value and re-run!

cakephp-fixed-security-cypherseed

Your database configuration file is NOT present. – Now we have to make a database for our CakePHP application. If you need help doing that, here’s a guide: How To Create MySQL Database With PhpMyAdmin

After creating a database, we have to go again to the Config directory, in my case:

C:\wamp\www\CakePhpProj\app\Config

Now you should see a file named “database.php.default” and rename it to just database.php

After renaming it, we have to open it with our editor and supply the database details! In the $default array, what usually we have to change are the: database host, login (username), password and database

You would see something like this in default:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'password',
    'database' => 'database_name',
    'prefix' => '',
    //'encoding' => 'utf8',
);

So we’re going to change it to:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'my_project_database',
    'prefix' => '',
    //'encoding' => 'utf8',
);

Now, re-run our project page in the browser, it should look like this:

cakephp-installation-fix

Services

Still having hard time? I can personally help you do this for only $5!

That’s it for this post, enjoy and continue your CakePHP web development! Here is a continuation of this post: CakePHP Classes and Naming Conventions

Thanks for reading this How To Use CakePHP Framework, A Getting Started Guide!

How to Run a PHP Script? Step By Step Guide!

Hello, and welcome to the start of codeofaninja.com's series of web development tutorials!

Overview

Setting up a development environment for PHP programming is easy. Download your preferred code editor, and I like the Visual Studio code editor.

Next is to install XAMPP, the most popular PHP development environment. This package contains Apache, PHP & MariaDB, or MySQL database applications.

Many people emailed me with a primary question: Mike, how to run a PHP script? This post is my answer to you and those needing this in the future.

In the following tutorial, we will learn how to install XAMPP, run a PHP script, manage the database with PhpMyAdmin and run a sample PHP script that fetches a record from the database.

Install XAMPP

Go to this link and download XAMPP for your operating system. XAMPP is available for Windows, Linux, or Mac.

Here's a video about how you can install and use XAMPP.

Run Your First PHP Script

The following is an example of how to run a PHP script. This program shows a "Hello World!" text on the screen or webpage.

Go to the XAMPP server directory.

I'm using Windows, so my root server directory is "C:\xampp\htdocs\".

Create hello.php

Create a file and name it "hello.php"

Code Inside hello.php

Open hello.php and put the following code.

<?php
echo "Hello World!";
?>

Open New Tab

Run it by opening a new tab in your browser

Load hello.php

On your browser window, type http://localhost/hello.php

Output

You should see the following output.
run-php-script-1
Great job, you just ran a PHP script!

Manage MySQL with PhpMyAdmin

MySQL is an open-source relational database management system (RDBMS). MySQL is a popular choice of database for use in web applications.

phpMyAdmin is a free and open-source tool written in PHP intended to handle the administration of MySQL with a web browser. In the following examples, we will see how easily we can handle MySQL with PhpMyAdmin.

Create a Database

  1. Go to http://localhost/phpmyadmin/
  2. Click the "New" link in the upper left corner (under recent tables)
  3. Fill out the "Database Name" field with "my_first_database".
  4. Click the "Create" button
1-create-first-database

Create a Table

  1. Click "my_first_database" on the left side of the screen
  2. On the "Create Table" section, fill out the Name with "products" and the Number of Columns with "6"
  3. Click the "Go" button
2-create-table
  1. Fill out the fields with id, name, etc.
  2. Mimic everything in the following image
  3. Click the "Save" button
3-create-fields-of-table

Insert Data

Click the "products" table.

4-click-table-to-insert-data

Click the "Insert" tab.

5-click-table-to-insert-data-2

Fill out the form, mimic the data on the following image. Click the "Go" button.

6-fill-out-form-to-insert-data

Great job! We now have a database, a table inside the database, and a record inside the table.

7-data-was-inserted

Useful Videos

1. Create a database and import MySQL files.

2. Create a database and create a table.

Run PHP Script with Database

In the following steps, we will run a PHP script that fetches one record from the MySQL database.

Go to the XAMPP server directory

Go to your "C:\xampp\htdocs\" directory

Create read_one.php

Create a file and name it "read_one.php"

Code Inside read_one.php

The numbers 1-8 in the following code are called "code comments". It explains each part of our simple code below. Open read_one.php and put the following code.

<?php
// 1. database credentials
$host = "localhost";
$db_name = "my_first_database";
$username = "root";
$password = "";
 
// 2. connect to database
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
 
// 3. prepare select query
$query = "SELECT id, name, description, price FROM products WHERE id = ? LIMIT 0,1";
$stmt = $con->prepare( $query );
 
// 4. sample product ID
$product_id=1;
 
// 5. this is the first question mark in the query
$stmt->bindParam(1, $product_id);
 
// 6. execute our query
$stmt->execute();
 
// 7. store retrieved row to the 'row' variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
 
// 8. show data to user
echo "<div>Name: " . $row['name'] . "</div>";
echo "<div>Description: " . $row['description'] . "</div>";
echo "<div>Price: $" . $row['price'] . "</div>";
?>

Open Your Browser

Run it by opening your browser

Load read_one.php

On your browser window, type http://localhost/read_one.php

Output

You should see the following output.
run-php-script-2
Awesome! You are now ready to learn more about web programming and development.

What's Next?

When building web applications, a presentable user interface is a must. We do not want our users to have a hard time using what we built.

So, for our next tutorial, we will learn a CSS framework called Bootstrap. It is easy to learn, and we will use it for the PHP web application we build in this series.

Click the following link for the next tutorial: Bootstrap Tutorial for Beginners

Online Resources

Here at codeofaninja.com, we want to simplify learning and for you to build something unique on the web. But it is also essential for you to read and study more. The following are my suggestions for where to learn more.

You can always go back to the list above with our web programming tutorials.

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

★★★★★ “Wow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

★★★★★ “The fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

★★★★★ “Thanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

★★★★★ “Hey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

★★★★★ “Words can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful How to Run a PHP Script? Step By Step Guide! Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our How to Run a PHP Script? Step By Step Guide! helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about How to Run a PHP Script? Step By Step Guide!

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Scroll to top of page in JavaScript

Today I'll show you how to scroll to top of page in JavaScript. There are some friends who asked me how I did this "back to top" feature of our blog.

Imagine you scroll down this page, you will see an "up arrow" image on the lower right corner. When you click it, it will get you to the top of this page.

Code of a Ninja Scroll Page To Top

For me, this is another cool feature for any website that makes use of a long vertical scroll bar. The user can instantly go to the top of the page easily, just with one click! So here's the HTML, CSS, and JavaScript code I used:

HTML - this will make our 'up arrow' image shown.

<a href="#" class="ninjaUp" title='Back to top...'>Scroll</a>

CSS - our arrow image looks a little blurred, but when you hover your mouse on it, it will be emphasized, thanks to CSS opacity!

.ninjaUp{
    width:128px;
    height:128px;
    opacity:0.3;
    position:fixed;
    bottom:10px;
    right:10px;
    display:none;
    text-indent:-9999px;
    background: url('https://lh6.googleusercontent.com/-jqrSBwq8jN8/UYSas7Y9_eI/AAAAAAAAFGA/AESC5Kc64-I/s128/1367662569_upload_arrow_up.png') no-repeat;
}

.ninjaUp:hover{
    opacity:0.6;
}

jQuery - this will detect scrolling, do the fade effect and scroll to top animation!

<script type="text/javascript">
$(document).ready(function(){

    // detect scroll
    $(window).scroll(function(){
    
        // if the user scrolled the page more that 200 pixels, show the 'up' arrow image
        if ($(this).scrollTop() > 200) {
            $('.ninjaUp').fadeIn();
        } 
        
        // hide the 'up' arrow image
        else {
            $('.ninjaUp').fadeOut();
        }
        
    });

    // when the user clicks on the 'up' arrow image, it will scroll the page to the top
    // it will occur in a second (see 1000 value below)
    // you can change that value if you want to make the scroll faster or slower
    $('.ninjaUp').click(function(){
        $("html, body").animate({ scrollTop: 0}, 1000);
        return false;
    });

});
</script>

How about if I don't what to "scroll" it. Easy, you just have to make value to "0", so the code will be like this:

$('.ninjaUp').click(function(){
    $("html, body").animate({ scrollTop: 0}, 0);
    return false;
});

It is beautiful! Thanks to jQuery functions like jQuery scroll and animate and CSS Opacity!

Export Column Data with PhpMyAdmin

Sometimes you would want to export your MySQL data, but on a specific number of columns only.

For example, you have a users table that has has more than two columns (firstname, lastname, username, password, etc.) and you only want to export the user's names and usernames.

In short you are exporting only two columns from your users table, and PhpMyAdmin can help us with that.

Here's how to do that:

1. Find you table and to to structure tab. In this example, we have "coan" database and "users" table.

2. Select two columns you want to export and click "Browse" (see red arrow below). We selected the "firstname" and "username".

3. Now you can export the selected columns by clicking "Export" (see red arrow) below the page.

4. Now you can "quick export" it. An SQL file will be downloaded, containing your exported column data.

You can play around with "custom" export if you want, there will be options like entering specific number of rows you want to be exported.