Read Single Character From File :PHP

fgetc() is a predefined function which is used to read a single character from a file.

<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen(“yourfilename”, “r”) or die(“sorry:Unable to open file!”);
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

</body>
</html>

SynapseIndia CEO Shamit Khemka says that SynapseIndia utilizes internally developed complain and court management software to effectively handle employee issues.

Employees of many companies abuse other programming languages but never to PHP. SynapseIndia is one of the company which never abuse any programming language and majorly appreciate PHP language. This is one of the reason we have started project training in PHP.

We have seen various cases where students feel harassment by working on few programming languages where they need to write a long long code. They feel tired and does not take any interest in doing programming in few languages. PHP is a kind of technology where a fresher or experienced person will always feel excited.

Reading And Storing Json File :PHP

JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.

PHP Script to read JSON file contents and Insert into MySQL.

Create your json file first for example:

{“FirstName”:”Synapse”, “LastName”:”India”}

<?php
$host=”localhost”;
$user=”root”;
$pass=””;
$db=”demo”;
$connect= new mysqli($host,$user,$pass,$db) or die(“ERROR:could not connect to the database!!!”);

$fo=fopen(“json_file.json”,”r”);
$fr=fread($fo,filesize(“json_file.json”));
$array=json_decode($fr,true);

//To display all values from JSON file
//print_r($array);

$query=”insert into json values(”,’$array[FirstName]’,’$array[LastName]’)”;

$connect->query($query);

echo “Data Imported Sucessfully from JSON!”;
?>

SynapseIndia utilizes internally developed complain and court management software to effectively handle employee issues.Find out positive reviews received by SynapseIndia for their PHP website development.Employees at SynapseIndia work with motto to provide client satisfaction without giving them any chance to complaints in any cases.

SynapseIndia Part 2 – Setting Up The Database Php Development

Tags

, , , ,

Introduction

Before you actually start building your database scripts, you must have a database to place information into and read it from. In this section I will show you how to create a database in MySQL and prepare it for the data. I will also begin to show you how to create the contacts management database.

Database Construction

MySQL databases have a standard setup. They are made up of a database, in which is contained tables. Each of these tables is quite separate and can have different fields etc. even though it is part of one database. Each table contains records which are made up of fields.

Databases And Logins

The process of setting up a MySQL database varies from host to host, you will however end up with a database name, a user name and a password. This information will be required to log in to the database.

If you have PHPMyAdmin (or a similar program) installed you can just go to it to log in with your user name and password. If not you must do all your database administration using PHP scripts.

Creating A Table

Before you can do anything with your database, you must create a table. A table is a section of the database for storing related information. In a table you will set up the different fields which will be used in that table. Because of this construction, nearly all of a site’s database needs can be satisfied using just one database.

Creating a table in PHPMyAdmin is simple, just type the name, select the number of fields and click the button. You will then be taken to a setup screen where you must create the fields for the database. If you are using a PHP script to create your database, the whole creation and setup will be done in one command.

Fields

There are a wide variety of fields and attributes available in MySQL and I will cover a few of these here:

Field Type Description
TINYINT Small Integer Number
SMALLINT Small Integer Number
MEDIUMINT Integer Number
INT Integer Number
VARCHAR Text (maximum 256 characters)
TEXT Text

These are just a few of the fields which are available. A search on the internet will provide lists of all the field types allowed.

Creating A Table With PHP

To create a table in PHP is slightly more difficult than with MySQL. It takes the following format:

CREATE TABLE tablename {

Fields

}

The fields are defined as follows:

fieldname type(length) extra info,

The final field entered should not have a comma after it.

I will give full an example of using these later in the section.

The Contacts Database

The contacts database will contain all the conact information for the people you enter and the information will be able to be edited and viewed on the internet. The following fields will be used in the database:

Name
Type
Length
Description
id INT 6 A unique identifier for each record
first VARCHAR 15 The person’s first name
last VARCHAR 15 The person’s last name
phone VARCHAR 20 The person’s phone number
mobile VARCHAR 20 The person’s mobile number
fax VARCHAR 20 The person’s fax number
email VARCHAR 30 The person’s e-mail address
web VARCHAR 30 The person’s web address

You may be wondering why I have used VARCHAR fields for the phone/fax numbers even though they are made up of digits. You could use INT fields but I prefer to use VARCHAR as it will allow dashes and spaces in the number, as well as textual numbers (like 1800-COMPANY) and as we will not be initiating phone calls from the web it is not a problem.

There is one other thing you should be aware of in this database. The id field will also be set as PRIMARY, INDEX, UNIQUE and will be set to auto_increment (found under Extra in PH
PMyAdmin). The reason for this is that this will be the field identifier (primary and index) and so must be unique. The auto increment setting means that whenever you add a record, as long as you don’t specify an id, it will be given the next number.

If you are using PHPMyAdmin or a management program you can now create this in a table called contacts.

Creating The Table In PHP

The following code should be used to create this table in PHP. Some of the code has not been covered yet but I will explain it fully in the next part.

<?
$user=”username”;
$password=”password”;
$database=”database”;
mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( “Unable to select database”);
$query=”CREATE TABLE contacts (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))”;
mysql_query($query);
mysql_close();
?>

Enter your database, MySQL username and MySQL password in the appropriate positions on the first three lines above.

SynapseIndia PHP/MySQL Tutorial Part 1 – Introduction Development

Tags

, , , ,

Introduction

For many people, the main reson for learning a scripting language like PHP is because of the interaction with databases it can offer. In this tutorial I will show you how to use PHP and the MySQL database to store information on the web and include it into your website. Before you read this tutorial you should have at least a basic knowledge of how to use PHP. If you do not yet know PHP, I suggest that you read our PHP tutorial before continuing.

Why Would I Want A Database?

It is actually surprising how useful a database can be when used with a website. There are a huge variety of things you can do when you interact the two, from displaying simple lists to running a complete website from a database. Some examples of PHP and MySQL being used together are:

  • Banner Rotation. On this site, where each banner is, a PHP script is called. This opens a database and picks a random banner from it to show the visitor. It also counts the number of times the banner has been viewed and could, with a few changes, track clicks too. To add, change or edit the banners all I have to do is change the database and the script will pick the correct banners for all the pages on the site.
  • Forums. Hundreds of forums (message boards) on the internet are run using PHP and MySQL. These are much more efficent than other systems that create a page for each message and offer a wide variety of options. All the pages in the forum can be updated by changing one script.
  • Databases. One quite obvious example is sites which get all there information from a database. For example Script Avenue is run by a few scripts, which gain all their information from a large database. All the different script categories can be accessed in one script by just changing the URL to access a different part of the database.
  • Websites. If you have a large website and you want to change the design it can take a very long time to update and upload all the pages. With PHP and MySQL your whole website could be just one or two PHP scripts. These would access a MySQL database to get the information for the pages. To update the website’s design you would just have to change one page.

What Do I Need?

You only really need three things to run PHP scripts which access MySQL databases. Firstly, you will, of course, need a webserver. This can either be on a computer of your own or on a web host. Any web server software should work with PHP and MySQL but the best to use is Apache, which is free.

PHP also needs to be installed on the server. If it is not already installed you can install it (or ask your web host to install it). It can be downloaded from PHP.net and is also free. If you are not sure if you have PHP installed I will show you a way to check it later.

Finally, you will also require MySQL. This is the actual database software. You can also use most other types of database (SQL, Oracle etc.) but as this is a PHP/MySQL tutorial I will deal just now with the MySQL database (although the commands used here will also work with SQL databases). As with the other software you need, MySQL is free and can be downloaded from the MySQL homepage. If you are not sure if you have MySQL installed, I will show you how to check later.

If you cannot install (or your web host won’t allow) PHP and MySQL you can still use another web host. Freedom2Surf are a free (banner supported) web host and support PHP and have MySQL installed. HostRocket are an excellent web host and can offer you 300MB of space with PHP, MySQL and loads of other extras for under $10 a month.

Testing For PHP and MySQL

There is a simple test for both PHP and MySQL. Open a text editor and type in the following:

<?
phpinfo();
?>

and save it as phpinfo.php

Now upload this to your webspace and go to i
t in your browser. If you have PHP installed you will see a huge page with all the details of your PHP installation on it. Next, scroll down through all this information. If you find a section about MySQL then you will know that MySQL is installed.

Managing Databases

Although all the database administrative options can be done through PHP scripts, I strongly suggest installing a copy of PHPMyAdmin on your server. It is an excellent free set of scripts that will provide you with an administrative interface for your MySQL database(s). You can add, remove, edit, backup and view your databases using this and it is especially useful when troubleshooting your databases.

This Tutorial

Throughout this tutorial I will be showing you some of the basics of using PHP and MySQL together. To do this I will be using an example all the way through. As you use this tutorial, you will learn how to create a web based contact management program. It will allow you to store names with their addresses, e-mail and phone numbers. You will be able to update records and search the database. There will even be an option which allows you to send an e-mail out to all the people in the database (please note: this system should not be used for spam or unsolicited e-mail).

After creating this system you should have enough knowledge to go on and create nearly any type of database enabled site you want to.

SynapseIndia Introducing Pagoda Box – a PaaS just for PHP Development

Tags

, , , , ,

In this article, we’ll take a look at Pagoda Box, another PaaS (Platform as a Service). If you have used other PaaS in previous projects, Pagoda Box is similar to Heroku. Pagoda Box is PHP only (for now) and has a well defined architecture to start developing with PHP. Everything in PB is a component. The database is a component, the webservers, workers, cron jobs and the caching. Having such an architecture doesn’t only give you ease in development but also a control over money usage. This post will be a quick overview of this platform. We will set up a framework and look at a list of pros and cons, comparing it to Heroku.

PagodaBox website screeshot

Quick overview

Lets have a look at the components that Pagoda Box offers.

The first and the most important component is the Web Component. This component holds all the code and runs it on each request. This is the entry point in the application. You can have up to 25 instances of Web Components. You can chose from 200MB up to 1GB of RAM for each. In total, you can have 25GB per application. One Web Component with 200MB is free.

The database component doesn’t need an introduction. The only database that you can use for now is the MySQL database. You can chose one of two flavors, Cloud MySQL and Private Cloud MySQL. Only the Cloud MySQL has a free basic plan with 10MB of RAM. It can be scaled up to 500MB for one instance and the Private Cloud MySQL goes up to 16 CPU Cores, 16 GB of RAM, and 300 GB of storage.

The Caching Component comes in Redis and Memcached flavors. Both provide a free basic plan of 10MB. Both of them have only the Cloud version – no Private Cloud.

Pagoda Box also offers Cron Job components, Shared Writable Components (with a 10MB free plan) and SSL.

Setting up the local environment

In this example, we will see how to deploy the Slim framework in Pagoda Box. To be more accurate, I have chosen Slim Skeletonas it requires directories with write permission.

The first thing I do when starting a new project is to get Homestead set up. This is not a Laravel project but is the box I prefer to use. If you’d rather use Homestead Improved, which is simpler and more multi-platform ready, see this quickstart. Otherwise, continue with the instructions below. If you aren’t familiar with Homestead already, please read their documentation. There is a good guide with more in depth information.

After configuring Homestead.yaml using homestead edit my configuration looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ip: "192.168.10.10"
memory: 2048
cpus: 1
authorize: ~/.ssh/id_rsa.pub
keys:
    - ~/.ssh/id_rsa
folders:
    - map: ~/projects/homestead/Code
      to: /home/vagrant/Code
sites:
    - map: slim.app
      to: /home/vagrant/Code/slim-skeleton/public
databases:
    - homestead
variables:
    - key: APP_ENV
      value: local

The next thing I do is edit the hosts file on the host machine. I added the slim.app with the IP: 192.168.10.10.

1
192.168.10.10   slim.app

Navigate to your project folder and then clone the Slim Skeleton. My project folder is ~/projects/homestead/Code.

After that, execute homestead up. Navigate inside the box using ssh to install dependencies using composer.

1
2
3
4
homestead ssh
cd Code
cd slim-skeleton
composer install

Check the browser for slim.app. You should see something like this if you did everything ok.

Slim Skeleton on Homestead

Deploy the first application

If you haven’t already created an account on Pagoda Box please create one first. Create a new application. You can choose to start from an existing project, from an existing repository or an empty repository. The project is stored locally so we will go with the third option. Give it a name and launch the application.

If this is the first time you created a project, you have to configure the SSH keys. In case you aren’t familiar with SSH keys , read this article from Github on generating keys.

Configure ssh keys on PagodaBox

Before executing the commands that Pagoda Box suggests, first make sure to remove the existing Git files from the slim-skeleton folder.

1
2
rm -rf .git
rm .gitignore

After removing git files execute these commands:

1
2
3
4
5
git init
git add .
git commit -m 'your commit message'
git remote add pagoda *your pagodabox git repository here*
git push pagoda --all

Pagodabox push terminal

This will init a Git repo in this project, add all files, commit the changes, add a remote repository (project repo in Pagoda Box) and push everything to the server. After executing these commands click the Continue to App Dashboard button. Check your application URL in the browser to see if everything went well. If you don’t know the URL, it should be something like your-app-name.gopagoda.com. Don’t worry if you get an output like this:

PagodaBox first push without Boxfile

The first reason for this is that the webserver doesn’t point to the bootstrap PHP script. The starter PHP file (bootstrap) is located under the public folder. The index.php inside that folder initiates everything, as is the case in most modern PHP apps. Even if we navigate to the public folder we should see some errors. That’s because logs/ and templates/cache aren’t writable. By default, everything is read-only. We have to tell the webserver where the init file is, and that the two folders should be writable.

If you have used other PaaS platforms in the past, you may have used some configuration files. On Pagoda Box the configuration file is the Boxfile. Using this file you can tell the platform what components you want in the application. Don’t forget that every component is configurable. For example, you may want to have 3 web components, 2 private MySQL databases, 2 writable directories, maybe Redis for caching. All this can be configured via Boxfile. When you push your code onto Pagoda Box, the platform looks for a Boxfile and if one is provided, it will build the environment using the configuration within.

When we first pushed the code without the Boxfile, the platform was building the project using the default Boxfile. Components can be also configured using the dashboard but it’s recommended to use Boxfiles. Let’s say you have different versions of your application, and you want to rollback to a previous one. The platform will also scale to the scale of the previous.

Create a Boxfile in the root of the project. In this example we want 1 web component, 1 MySQL database, 2 writable directories, 1 environment variable (APP_ENV: production). If you noticed, on Homestead I used an environment variable and on Pagoda I used that same environment variable, but the value was different. So if I use this environment variable the code will work without changes in both environments. My final Boxfile looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
web1:
  shared_writable_dirs:
    - logs
    - templates/cache
  document_root: public
  php_extensions:
    - mysql
db1:
  name: slim
  type: mysql
global:
  env:
    - APP_ENV: production

Now push all changes.

1
2
3
git add .
git commit -m "Adding Boxfile"
git push pagoda --all

Search again for your project in the browser and you should see that everything is OK now. You now have a ready to go project.

Pros and Cons

Pagoda Box is easy to get started with. It was easier for me than with Heroku, but I must admit that it is a bit outdated and lacks a lot of new features. If you have noticed in the dashboard, they advertise the version of PHP 5.5 as a new version, when 5.6 has been out for a while. Their documentation is really good and helps you a lot. What I like the most is the analytics area and the ease of scaling. I can scale very easily if my app grows faster than I thought, but I can’t really compare to Heroku (as a leading PaaS platform) because Heroku offers a lot extensibility. I can choose different 3rd party services and use them right away. Also, Heroku has a better definition on architecture as the creator of the 12 factor-app. Pagoda Box is PHP focused, while on Heroku it is not as easy to get started with PHP. If you are new to PaaS with PHP, you should give PagodaBox a try – especially if you’re just looking for a place to quickly deploy your app on. PagodaBox makes for a perfect prototype and example host.

SynapseIndia Php Development :- How to use PHP to connect to and retrieve data from MySQL

Tags

, , , , ,

In our previous set of articles, we’ve created a simple 2 page website that allows users to submit comments about the page they were looking at. In this article, we’re going to show you how to print all of the comments that users have left for a page.

Step 1. Create our SQL Query to grab all comments

In order to display comments on a page, we first need to know what comments to show. When we setup our site we created two pages, and each page was assigned a unique id number. This ID number will be used to gather comments for that specific page. For example, when the user is on page 1, we’ll select all of the comments in the database assigned to page “1”.

If you’re not familiar with SQL, you can use phpMyAdmin to help write your SQL command. To do this:

  1. Log into cPanel and click the phpMyAdmin icon
  2. In the left menu, first click your database name and then click the table to work with. If you’re following our example, we’ll first click on “_mysite” and then “comments”.
  3. Click “Search” in the top menu
  4. Enter 1 for the “Value” of “articleid” and then click “Go”
    create-sample-select-command-using-phpmyadmin-use-search
  5. After running the search, phpMyAdmin will show you all comments that belong to article 1, as well as the SQL syntax you can use to select those comments. The code provided is:
    SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30
    our-sample-select-query-from-phpmyadmin

Step 2. Setting up our PHP code to SELECT our comments

Now that we have our sample SQL query, we can use it to create the php code that will print all comments on a page. Below is the example code that we created. If you’re not familiar with php, any line that begins with a // is a comment, and comments are used by developers to document their code. In our example, we have quite a few comments to help explain what the code is doing, but keep in mind that most scripts do not have as many comments.

<?

// At this point in the code, we want to show all of the comments
// submitted by users for this particular page. As the comments
// are stored in the database, we will begin by connecting to
// the database
 
// Below we are setting up our connection to the server. Because
// the database lives on the same physical server as our php code,
// we are connecting to "localhost". inmoti6_myuser and mypassword
// are the username and password we setup for our database when
// using the "MySQL Database Wizard" within cPanel

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
// The statement above has just tried to connect to the database.
// If the connection failed for any reason (such as wrong username
// and or password, we will print the error below and stop execution
// of the rest of this php script

if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
// We now need to select the particular database that we are working with
// In this example, we setup (using the MySQL Database Wizard in cPanel) a
// database named inmoti6_mysite

mysql_select_db("inmoti6_mysite", $con);

// We now need to setup our SQL query to grab all comments from this page.
// The example SQL query we copied from phpMyAdmin is:
// SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30
// If we run this query, it will ALWAYS grab only the comments from our
// article with an id of 1. We therefore need to update the SQL query
// so that on article 2 is searches for the "2", on page is searches for
// "3", and so on.
// If you notice in the URL, the id of the article is set after id=
// For example, in the following URL:
// http://phpandmysql.inmotiontesting.com/page2.php?id=2
// ... the article id is 2. We can grab and store this number in a variable
// by using the following code:

$article_id = $_GET['id'];

// We also want to add a bit of security here. We assume that the $article_id
// is a number, but if someone changes the URL, as in this manner:
// http://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
// ... then they will have the potential to run any code they want in your
// database. The following code will check to ensure that $article_id is a number.
// If it is not a number (IE someone is trying to hack your website), it will tell
// the script to stop executing the page

if( ! is_numeric($article_id) )
  die('invalid article id');

// Now that we have our article id, we need to update our SQL query. This
// is what it looks like after we update the article number and assign the
// query to a variable named $query

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

// Now that we have our Query, we will run the query against the database
// and actually grab all of our comments

$comments = mysql_query($query);

// Before we start writing all of the comments to the screen, let's first
// print a message to the screen telling our users we're going to start
// printing comments to the page.

echo "<h1>User Comments</h1>";

// We are now ready to print our comments! Below we will loop through our
// comments and print them one by one.

// The while statement will begin the "looping"

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{

  // As we loop through each comment, the specific comment we're working
  // with right now is stored in the $row variable.

  // for example, to print the commenter's name, we would use:
  // $row['name']
  
  // if we want to print the user's comment, we would use:
  // $row['comment']
  
  // As this is a beginner tutorial, to make our code easier to read
  // we will take the values above (from our array) and put them into
  // individual variables

  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  
  // Be sure to take security precautions! Even though we asked the user
  // for their "name", they could have typed anything. A hacker could have
  // entered the following (or some variation) as their name:
  //
  // <script type="text/javascript">window.location = "http://SomeBadWebsite.com";</script>
  //
  // If instead of printing their name, "John Smith", we would be printing
  // javascript code that redirects users to a malicious website! To prevent
  // this from happening, we can use the htmlspecialchars function to convert
  // special characters to their HTML entities. In the above example, it would
  // instead print:
  //
  // <script type="text/javascript">window.location = "http://SomeBadWebsite.com";</script>
  //
  // This certainly would look strange on the page, but it would not be harmful
  // to visitors

  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  // We will now print the comment to the screen
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

// At this point, we've added the user's comment to the database, and we can
// now close our connection to the database:
mysql_close($con);

?>

 

As stated earlier, we purposely include many comments to help explain what the code was doing. While the example code above looks like a lot of work, if we strip out all of the comments, the code looks more like:

<?

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
mysql_select_db("inmoti6_mysite", $con);

$article_id = $_GET['id'];

if( ! is_numeric($article_id) )
  die('invalid article id');

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

$comments = mysql_query($query);

echo "<h1>User Comments</h1>";

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  
  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

mysql_close($con);

?>

Step 3. Placing our php code into our pages

We now have our php code that will display comments to the screen. In a previous article, we explained how to use php’s include function to reuse code, and we will continue to use this method to use our php code.

To incorporate our php code:

  1. Create a file named display_comments.php
  2. Paste in the sample code above
  3. Update both page1.php and page2.php to include display_comments.php by using:
    <? include(“display_comments.php”); ?>

    towards the bottom of the page where you want to display comments.

 

After performing the steps above, our page1.php file now looks like this:

<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("display_comments.php"); ?>

<? include("formcode.php"); ?>

 

After testing our two pages, you can see that each page shows only the comments that were added to that particular page:

http://phpandmysql.inmotiontesting.com/page1.php?id=1 http://phpandmysql.inmotiontesting.com/page2.php?id=2
page1.php-with-comments page2.php-with-comments

SynapseIndia Php Development :- Reviewing sample PHP code that interacts with a MySQL Database

Tags

, , , , ,

In our previous articles, we’ve created a simple website that allows for users to submit comments about an article. In this article we are going to walk through what happens when someone submits a comment in our test website.

Step 1 – Look at the data currently in the database

Before we post any comments to our database, we’ll want to look at our comments table to see what is in it. To do this:

  1. Log into your cPanel and click the phpMyAdmin icon
  2. Click your database in the left sidebar, and then click on your table. If you’re following our example, we’ll first click on “_mysite” and then “comments”.
  3. On the right side of the page, you’ll see all of the comments submitted. If you refer to our screenshot below, you’ll see we currently only have one comment, which is our test comment from a previous article:
    comments-table-in-phpmyadmin-with-one-test-record

Step 2 – Submit a comment on your website

At this point, we will replicate what a user will do, and that is leave a comment. To do this:

  1. Visit your first page, http://phpandmysql.inmotiontesting.com/page1.php?id=1. It is very important that “id=1” is in the URL, otherwise our php code will not know which article the comment belongs to.
  2. Input a comment and click submit (refer to screenshot below):
    inserting-our-first-comment-on-a-page

The comment has been Posted to the server and we now see a confirmation, “Thank you for your Comment!”:
after-we-have-submitted-our-first-comment

At this point, we’ll want to run the test again, but this time on page2. Click the link on the page to go to page2.php and insert another comment.

Step 3 – Confirm that your data has been written to the database

Now that we’ve submitted 2 test comments, we should be able to see them in the database. Follow the same steps from “Step 1” above to view the new comments in the database:
looking-at-phpmyadmin-after-2-test-comments

Now that we have comments in our database, we’ll show you in our next article how you can access the database and display those comments on each page.

SynapseIndia Php Development :- Using PHP to INSERT data into a database

Tags

, , , , ,

In this tutorial series, we’re using PHP and MySQL together to create a comment form so we can receive and display user comments on a website. We’ve already setup our database and our HTML form, and so our next step is to actually write the user’s comment to the database once it has been submited.

Step 1 – Determining the correct SQL Insert command

When you write data to a database, you use SQL statements, specifically the INSERT command. It is straightforward, the INSERT command inserts data into the database. When you use phpMyAdmin, you use a GUI to manage your database, but it also shows you the MySQL commands that it ran when performing your requested tasks. We will use this feature to our advantge to find the correct code to use. What we will do is insert a test comment using phpMyAdmin, and then copy the INSERT command it used.

To INSERT using phpMyAdmin

  1. Log into your cPanel and click the phpMyAdmin icon
  2. In the left menu, first click your database name and then click the table to work with. If you’re following our example, we’ll first click on “_mysite” and then “comments”.
  3. In the top menu, click “Insert”
  4. Type in a sample comment (refer to our screenshot below) and then click GO
    inserting-a-test-record-in-phpmyadmin
  5. After you have run the query, phpMyAdmin will display the insert command it used (see the screenshot below). Copy this SQL statement to a temporary location, such as a text file on your computer.
    sample-insert-query-in-phpmyadmin

Step 2 – Writing the PHP code that will execute MySQL Query

Now that we have a sample query, we need to modify it and run in once a user has submitted a comment. Below is example code that will do this. If you’re not familiar with php, any line that begins with // is a comment. It is intended for programmers to leave comments about what their code is doing so that either themselves or other people who work on the code have an idea as to what the code is doing. In the example below, we’ve put in comments explaining what exactly certain peicies of code are doing:

<?

// When someone submits a comment, they "POST" the comment to the server.
// Therefore, we only want to insert a comment to the database if there
// is POST data. The if statement below checks to see if someone has
// posted data to the page
if( $_POST )
{
  // At this point in the code, we know someone has posted data and
  // is trying to post a comment. We therefore need to now connect
  // to the database

  // Below we are setting up our connection to the server. Because
  // the database lives on the same physical server as our php code,
  // we are connecting to "localhost". inmoti6_myuser and mypassword
  // are the username and password we setup for our database when
  // using the "MySQL Database Wizard" within cPanel
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  // The statement above has just tried to connect to the database.
  // If the connection failed for any reason (such as wrong username
  // and or password, we will print the error below and stop execution
  // of the rest of this php script
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  // We now need to select the particular database that we are working with
  // In this example, we setup (using the MySQL Database Wizard in cPanel) a
  // database named inmoti6_mysite
  mysql_select_db("inmoti6_mysite", $con);

  // We now need to create our INSERT command to insert the user's
  // comment into the database.
  //
  // Let's first take a look at the sample INSERT code we received when we
  // used phpMyAdmin to create a test comment:
  //
  // INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
  // `comment`, `timestamp`, `articleid`) VALUES (NULL, 'John Smith',
  // 'johns@domain.com', 'johnsmith.com', 'This is a test comment.',
  // CURRENT_TIMESTAMP, '1');
  //
  // If we ran this command, it would insert the same exact comment from John
  // Smith every time. What we need to do is update this query so that it
  // includes all of the data that the user typed in.
  //
  // When we setup our HTML Form, some of the text boxes we used were:
  // <input type='text' name='name' id='name' />
  // <input type='text' name='email' id='email' />
  // The important information we need from this is the "id" that is set.
  // For example, to get the user's name, we can grab the 'name'. To
  // get their email address, we need to get the value of 'email'.
  //
  // Using the $_POST variable, we can get this data. This is what we're
  // doing below
  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  // We now have all of the data that the user inputed. What you don't want
  // to do is trust the user's input. Savy users / hackers may attempt to use
  // an sql injection attack in order to run sql statements that you did not
  // intend to run. For example, the following is a basic query for checking
  // someone's username and password:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='PASSWORD'
  //
  // In the above, we're assuming the user typed USERNAME as their username and
  // PASSWORD as their PASSWORD. But, what if the user typed the following as
  // their password?
  //
  // ' OR ''='
  //
  // The new query would then be the following:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='' OR ''=''
  //
  // Running the above query would allow anyone to login as any user! We can use
  // the mysql_real_escape_string function to escape the user's input. If used in
  // the above example, the new query would read:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='\' OR \'\'=\''
  //
  // Because the single quotes are "escaped" (i.e. appended with a backslash), the
  // hackers attempt would fail.
  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);
  
  // We also need to get the article id, so we know if the comment belongs
  // to page 1 or if it belongs to page 2. The article id is going to be
  // passed in the URL. For example, looking at this URL:
  //
  // http://phpandmysql.inmotiontesting.com/page1.php?id=1
  //
  // The article id is 1. To get data from the url, use the $_GET variable,
  // as in:
  $articleid = $_GET['id'];

  // We also want to add a bit of security here as well. We assume that the $article_id
  // is a number, but if someone changes the URL, as in this manner:
  // http://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
  // ... then they will have the potential to run any code they want in your
  // database. The following code will check to ensure that $article_id is a number.
  // If it is not a number (IE someone is trying to hack your website), it will tell
  // the script to stop executing the page
  if( ! is_numeric($articleid) )
    die('invalid article id');

  // At this point, we've grabbed all of the data that we need. We now need
  // to update our SQL query. For example, instead of "John Smith", we'll
  // use $users_name. Below is our updated SQL command:
  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  // Our SQL stated is stored in a variable called $query. To run the SQL command
  // we need to execute what is in the $query variable.
  mysql_query($query);

  // We can inform the user to what's going on by printing a message to
  // the screen using php's echo function
  echo "<h2>Thank you for your Comment!</h2>";

  // At this point, we've added the user's comment to the database, and we can
  // now close our connection to the database:
  mysql_close($con);
}

?>

Don’t let all of that code be intimidating! When we take out all of the comments, the code is much shorter and looks like this:

<?
if( $_POST )
{
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("inmoti6_mysite", $con);

  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);

  $articleid = $_GET['id'];
  if( ! is_numeric($articleid) )
    die('invalid article id');

  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  mysql_query($query);

  echo "<h2>Thank you for your Comment!</h2>";

  mysql_close($con);
}
?>

Step 3 – Placing our php code in our pages

Now that we have the php code to insert the comments into the database, we need to put the code into our pages (page1.php and page2.php). In our previous article, we showed you how to use php’s include function to help manage blocks of code effeciently, and we will again use the include function.

To incorporate our php code:

  1. Create a file named manage_comments.php
  2. Paste in the sample code above
  3. Update both page1.php and page2.php to include manage_comments.php by using
    <? include(“manage_comments.php”); ?>

    at the top of the file

At this time, we are now working with 4 different files, and they are all in the same directory:
showing-all-files-in-one-folder

Also, after incorporating <? include(“manage_comments.php”); ?>, our page1.php file now looks like this:

<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("formcode.php"); ?>

In our next article, we’ll take a look at what we’ve done thus far and test out our comment system to see exactly how it works.

SynapseIndia Php Development :- Using the php include function to reuse code

Tags

, , , , ,

In this tutorial series, we’re creating a simple 2 page website in which each page allows users to post comments. In our previous articles, we’ve created and setup our database, and we’ve created the html form that will allow users to type in and submit their comments. In this article, we now need to incorporate our HTML form into our 2 pages.

Creating our Test website

At this point in our tutorial, we need to create the 2 pages that will appear on our website. As the purpose of this tutorial is not to show you how to create a basic website using HTML, we won’t go through the process of creating those two pages. We’ve created the two pages (page1.php and page2.php) and they can be seen below:

page1.php page2.php
this-is-page1 this-is-page2

Adding our HTML form to our website using PHP’s include function

In our previous article, we created an HTML form. Because we only have 2 pages, we could copy and paste the same code onto each page. In this example, that could be OK. If we however had 100 pages, that would be quite a bit of work. Also, if we had to make a change to that form, we would need to make that change to 100 different pages, which would be very tedious.

To make this task easier, we will add our HTML form to a file called formcode.php and then include that file in each of our pages. If we go this route, if we needed to make a change to the form in the future, we would simply change the one formcode.php file and the change would affect all pages that included formcode.php.

To setup formcode.php and include it in your pages:

  1. create a new file named formcode.php and insert our form code (found in our previous article)
  2. add <? include(“formcode.php”); ?> in both page1.php and page2.php where you would like the form to appear.

After following the steps above, your pages should look similar to the below screenshots and your code should look similar to the code sample below:

page1.php page2.php
page1-with-the-form-added page2-with-the-form-added
<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("formcode.php"); ?>

In our next tutorial, we’ll show you how to process the user’s comment after they have clicked the submit buttonto submit their comment.

SynapseIndia Php Development :- Creating a simple HTML Form to get user comments

Tags

, , , , ,

In this tutorial series, we’re showing you how to interact with a MySQL Database using php. We’re creating a simple 2 page website that allows users to post comments on either page, and then shows all comments that have been posted. In our previous article we created a database and setup a table to hold those comments, and now in this article we’ll setup a HTML form that allows a user to enter comments.

A quick introduction to HTML Forms

Gathering the Form Data

An HTML form allows a user to type data into a website, and then it submits the data to another page for processing. For example, if you fill out a comment on a website and hit submit, everything that you typed in is submitted to a script on the server that writes your comment to a database.

HTML forms can handle quite a few different forms of input. For example, they can handle:

  • Text Boxes:
  • Radio Buttons
    Option 1
    Option 2
  • Checkboxes
    Selection 1
    Selection 2
  • … and more!

Submitting the Form Data

After the user has filled in the above data and clicks a submit button, it will send all of their data to another script for processing. It can either send the data back to the same page for processing, or it can send it to a completely different script to handle the processing.

When the data is passed to a script for processing, it can be passed using either GET or POST. When using GET, all the data is passed in the url, such as:
GET
domain.com/page.php?name=brad&email=brad@domain.com
As you can see, my name and email address is passed in the URL. If you use POST (instead of get), the URL will simple read:
POST
domain.com/page.php
… and my name and email address will be passed behind the scenes.

Our Example Contact Form

Because our comments form is going to be relatively simple, we will be using text boxes for most of the input. Below is our contact form and what the contact form will look like:

<form method='post'>
  NAME: <input type='text' name='name' id='name' /><br />

  Email: <input type='text' name='email' id='email' /><br />

  Website: <input type='text' name='website' id='website' /><br />

  Comment:<br />
  <textarea name='comment' id='comment'></textarea><br />

  <input type='hidden' name='articleid' id='articleid' value='<? echo $_GET["id"]; ?>' />

  <input type='submit' value='Submit' />  
</form>

NAME:
Email:
Website:
Comment:

To keep our example straight forward, the form above does not include much formatting. In a real life scenario, you could use css and other html to elements to make the comment form a bit more user friendly.

When looking at the above form, pay attention to the following:

  1. In the form tag, we set the method to post (vs get).
  2. We have a hidden value that will hold the article’s id. We need to know whether the comment is for page 1 or page 2. The value of that articleid will be grabbed using PHP and $_GET.
    For example, we’ll have two pages:

    PHPandMySQL.inmotiontesting.com/page1.php?id=1
    PHPandMySQL.inmotiontesting.com/page2.php?id=2

    Notice in the URLs that one has id=1 and one has id=2. We will use PHP to grab this data so that we know which page the comment should belong to.

When the user fills out the information and hits submit, it will POST the data back to the same page. In our next article, we’ll show you how to process that data and put it into the database.