Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Run PHP Scripts – A Beginner’s Guide

INTRODUCTION
NOT DOUBLE CLICK

Welcome to a beginner’s tutorial on how to run PHP scripts. So you may have just started learning PHP, and realized that we don’t simply double click a PHP file to run it, neither does opening it in a browser work. Just how do we run PHP files then? Well, we will have to set up a development environment, Install and set certain things up first – This guide will walk you through all of it, step-by-step. Read on!

I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
Stuff to Install

Section B
Run PHP Script

Section C
Database Scripts

Section D
Command Line Run

Extra
Download & More

Closing
What’s Next?

SECTION A
STUFF TO INSTALL

To run PHP files, we will need to install PHP on the computer. But it is better if we just install a full suite of the web server, database, and PHP right from the start – That will save us the trouble from installing them one-by-one in the future.

Thankfully, we don’t have to download the individual components and install them one at a time. There is something called XAMPP, and it is a compilation of all the packages that we need to get started. Simply click here to download and install XAMPP for your operating system.

WHAT IS XAMPP AND A WEB SERVER STACK?

Let me just do a quick quote from WhatIs.com:

A Web stack is the collection of software required for Web development. At a minimum, a Web stack contains an operating system (OS), a programming language, database software and a Web server.

So yes, XAMPP is a web-server stack, and it stands for:

  • Cross-platform (x) – Works on Windows, Linux, and Mac.
  • Apache – An HTTP web server.
  • Maria DB – The database.
  • PHP – You should already know…
  • Perl – Another programming language.

Some of you guys may be wondering now – I just want to run PHP files, why the heck do we need so many components? Yep, the whole PHP situation can be rather confusing to total beginners. We can actually just install PHP and let it run independently in the command line.

But PHP has been traditionally made to be a web programming language, it is made to work with web servers, mail services, and databases. So, just as mentioned in the introduction above, installing all of these components right from the start will save you a lot of hassle in the future. But of course, you still have the choice to install PHP independently by itself, which I will not recommend.

INSTALLING A CODE EDITOR

Also, if you have not installed a good code editor yet, here is my list of recommendations on the free ones.

17 Best FREE HTML Editors (Windows, Linux, Mac)

SECTION B
RUNNING PHP SCRIPTS

Now that you have installed all the necessary stuff, it is time to create your first PHP script and run it in the web browser.

STEP 1) CREATING YOUR “HELLO WORLD” PHP SCRIPT

If you have properly installed XAMPP, then the root folder for the HTTP documents will be located at XAMPP/htdocs. Simply start by creating your “hello world” PHP script there.

XAMPP/htdocs/hello.php

STEP 2) FIRING UP XAMPP

Next, fire up the XAMPP Control Panel, and this is where you can switch the components on or off. Usually, we will only need the Apache web server and MySQL database server – So turn those on.

STEP 3) “RUN” FROM BROWSER

Finally, open your browser and navigate to http://localhost/hello.php – Congratulations! You have successfully installed a web server stack and run your first PHP script.

CHANGING THE HTTP ROOT FOLDER

Don’t like the default root folder? You can change it by editing a few lines of configuration. Go to the XAMPP Control Panel, hit the config button, and choose “Apache httpd.conf”. Look for the document root section, and change it to wherever you like.

httpd.conf
#DocumentRoot "D:/xampp/htdocs"
#
DocumentRoot "D:/http"

SECTION C
PHP SCRIPTS WITH DATABASE

Running PHP scripts is a piece of cake. Let us now take the example one step forward, and include some database action.

ACCESSING PHPMYADMIN – CREATING YOUR FIRST DATABASE

Another perk of XAMPP, is that a MySQL administration panel is already installed and you access it from http://localhost/phpmyadmin. Let us now use it to create your first database.

Simply click on “new”, name your database, then click on “create”. You will also notice that there are already a few other databases, and please do not mess with those… They contain some of the system setting stuff, and just leave them alone until you are 100% sure of what you are doing.

Next, select your newly created database, and click on the “SQL” tab. Copy the SQL code below, and hit “go”.

user.sql
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `user_email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`user_id`, `user_name`, `user_email`) VALUES
(1, 'John Doe', '[email protected]'),
(2, 'Jane Doe', '[email protected]'),
(3, 'Jay Doe', '[email protected]'),
(4, 'Joy Doe', '[email protected]'),
(5, 'Jess Doe', '[email protected]'),
(6, 'Jenn Doe', '[email protected]');

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `user_email` (`user_email`),
  ADD KEY `user_name` (`user_name`);

ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

Congratulations! You have just created your first database and dummy users table. Feel free to further explore the admin panel by yourself… but leave all that system stuff alone.

THE PHP-DATABASE SCRIPT

XAMPP/htdocs/hello-db.php
 PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES => false
    ]
  );
}

// ERROR WITH DATABASE CONNECTION - CRITICAL STOP - THROW ERROR MESSAGE
catch (Exception $ex) {
  print_r($ex);
  die();
}

// GET USERS FROM DATABASE
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
$users = $stmt->fetchAll();

// GENERATE HTML TABLE
echo "";
foreach ($users as $u) {
  printf("", $u['user_name'], $u['user_email']);
}
echo "
%s%s
"; // CLOSE DATABASE CONNECTION if ($stmt !== null) { $stmt = null; } if ($pdo !== null) { $pdo = null; }

Finally, create this script, access it http://localhost/hello-db.php, and watch it generate an HTML table from the database.

MYSQL? MYSQLI? PDO?

If you have already done some research on PHP database… or going to in the future, you will notice that there are a few ways to work with the database in PHP.

  • MySQL – mysql_connect(...). This is one of the most traditional MySQL libraries that is totally removed in PHP 7. If you see tutorials still using the old mysql library, just navigate away from that site… It is either very outdated or the author have absolutely no idea of what is going on.
  • MySQLi – mysqli_connect(...). This is the improved MySQL library. While it is common, I will not recommend this library, as it only supports MySQL.
  • PDO – What the example above uses, and what I recommend using. Now, PHP and MySQL go a long way back. But ever since then, a lot of different databases have risen to fame, and the developers pf PHP realized that they need to support more than just MySQL – The result is PDO, which supports a wide variety of database other than MySQL.

SECTION D
RUNNING FROM THE COMMAND LINE

For this final section, we will go into something a little more “advanced”. Yep, remember that we mentioned PHP can run independently in the command line? That is what we are going to do in this section.

COMMAND LINE POWER

Ladies and gentlemen, fire up your command prompt. Windows users, that is start > search for command prompt. Mac users, that is finder > terminal.

PHP in command line
D:\http\test>php hello.php
Hello World!
D:\http\test>

WHAT’S THE POINT?

So yes, we can run PHP from the command prompt, but what is it good for? What’s the point for this “roundabout” way? Well, to run scheduled PHP scripts – Send out newsletters, crunch some massive data, video processing in the background. The possibilities are endless… Beginners probably won’t be doing this command line thing, but just keep in mind that it is possible.

EXTRA
DOWNLOAD & RESOURCES

That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

REFERENCES

Here are a few links to references and stuff, if you want to learn more.

  • The official PHP manual
  • Learn PHP on W3Schools
  • Learn SQL on W3Schools

SOURCE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Run PHP Scripts – A Beginner’s Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Run PHP Scripts – A Beginner’s Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×