There are 4 stages in creating a PHP MySQL Script:
- Creating a PHP Connection to MySQL
- MySQL Table Creation
- Entering data in a MySQL table
- Displaying data from MySQL
However, before we start the steps above, there are several things we need to prepare, including:
- Install wampserver, how to do it HERE
- Creating a database, for further understanding you can see HERE
You can watch the short story of creating a database in the following video:
Once the two conditions above are met, then we can proceed to:
1. Creating a PHP Connection to MySQL
Open Notepad++ >> New, type the following code:
<?php
$hostmysql = "localhost";
$username = "root";
$password = "";
$database = "gatewan";
$conn = mysqli_connect ($hostmysql , $username , $password, $database);
if ($conn){
echo "<b> Koneksi Berhasil </b>";
}
else{
die ("<b> Koneksi Gagal </b>");
}
?>
Then save it with the filename "connect.php" and place it in the directory you created at: wampserver/www
Then open wampserver >> localhost, via Tray menu >> click your directory and select the file:
If the connection is successful
If connection fails
Information:
mysqli_connect is a function used to create a connection to a MySQL server using PHP. The data for the hostname, username, and password used have been declared by the variables $hostmysql, $username, $password, $database. It is the same as: mysqli_connect ("localhost","username","password","database");
if ($conn){...}
is a control statement used to test the connection to mysql.
2. MySQL Table Creation
Open Notepad++ >> New, type the following code:
<?php
include ("connect.php");
// sql untuk membuat tabel
$sql = "CREATE TABLE tamu (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo " Tabel tamu berhasil dibuat!";
} else {
echo " Pembuatan tabel gagal! : " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Then save it with the filename "table.php" and place it in the same directory, which you have created at: wampserver/www
Then open wampserver >> localhost, via Tray menu >> click your directory and select the file:
Before execution of table.php
The table.php execution process was successful
Database table results
Information:
include ("connect.php"); This command is used to include the connect.php file, as a requirement for the table creation process to go through the connection process first.
The specification of the data type that we will use for input is very important in creating a column. For example, the id column, because we will use the id as a reference, the value must be unique and the data type must be consistent, therefore we need to hold the column with the appropriate data type.
After that, we can define optional attributes for each column:
- NOT NULL - Each row must contain a value, and the values must not contain null.
- DEFAULT - Sets the default value or automatic value, when there is no data entry in a particular row.
- UNSIGNED - Used for number types, restricts data entry to positive values including zero.
- AUTO INCREMENT - MySQL will automatically increase the field value by +1 every time a new record is added.
- PRIMARY KEY - Uniquely used to identify a row in a particular table. Columns with PRIMARY KEY settings are usually used as IDs and use AUTO_INCREMENT.
Each table must have a primary key (in this case the "id" column) so its values must be unique.
3. Enter data in the MySQL table
Open Notepad++ >> New, type the following code:
<?php
include ("connect.php");
// sql entry data pada tabel
$sql = "INSERT INTO tamu (firstname, lastname, email)
VALUES ('Wawan', 'Beneran', 'admin@gatewan.com')";
if ($conn->query($sql) === TRUE) {
echo "User baru berhasil ditambahkan!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Then save it with the filename "insert.php" and place it in the same directory that you created at: wampserver/www
Then open wampserver >> localhost, via Tray menu >> click your directory and select the file:
Table before filling
Table insert process
Insert results for table
4. Displaying data from MySQL
Open Notepad++ >> New, type the following code:
<?php
include ("connect.php");
// sql menampilkan record
$sql = "SELECT id, firstname, lastname, email FROM tamu";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data setiap baris
while($row = $result->fetch_assoc()) {
echo "<br>". "id: ". $row["id"]. " - Name: ". $row["firstname"]. " ". $row["lastname"]. " - Email: ". $row["email"]. "<br>";
}
} else {
echo "Tidak ada data (kosong)!";
}
$conn->close()
?>
Then save it with the filename "show.php" and place it in the same directory you created at: wampserver/www
Then open wampserver >> localhost, via Tray menu >> click your directory and select the file:
Show data/record results
Information:
First, we setup SQL query to select id, firstname, lastname and email from guest table. Next line we declare $result variable to run the query $sql, of course after going through connection process ($conn).
Then, the num_row() function is used to check if there are more than 0 rows? If there are, then the fetch_assoc() function will place all the results into the array association, meanwhile, the while() loop block will repeat until all the data is displayed.
Reference:
- Dynamic Web Programming Module (Veria Yunianingsih.ST)
- http://www.w3schools.com/
Getting to Know PHP Control Statements
In C++ programming this is often known as "Repetition & Branching"
These three statements have the same basic form, namely:
pernyataan (syarat)
{
statement
}
IF
The IF construct is used to execute a statement conditionally, meaning a block of statements will be executed if it meets a certain condition, for example TRUE or FALSE or NULL, etc., depending on the desired condition.
Example:
<?php
$a=4;
$b=9;
if ($a>$b)
{
echo("a lebih besar dari pada b");
}
elseif ($a<$b)
{
echo("a lebih kecil b");
}
else
{
echo("a sama dengan b");
}
?>
WHILE
The WHILE construct is used to execute statements in a block of statements repeatedly, AS LONG AS the conditions are met.
In practice, the loop will evaluate the statement block as long as the condition is TRUE, and will stop if the condition is FALSE, meaning that the conditions used are correlated to the statement. One of the practices is like that.
Example:
<?php
$a=1;
while ($a<10)
{
echo($a);
$a++;
}?>
FOR
The FOR construction is also used for looping or repeating statements in a statement block, AS LONG AS the conditions are met, only the required conditions have 3 components, php calls it an expression (expr). Here is the basic form:
for (expr1; expr2; expr3)
{
statement
}
- expr1 is the initial initialization. In each iteration (looping process) this is the one executed first.
- expr2 is a condition/requirement. The next execution expr2 is evaluated, if it is TRUE, then the loop continues, if it is False then the loop is stopped.
- expr3 is a value changer. Finally expr3 is executed, the execution can be an addition or subtraction of value.
Example:
<?php
for ($a=0;$a<10;$a++)
{
echo("Nilai A = ");
echo("$a");
echo(" ");
}
?>
Reference
- Dynamic Web Programming Module (Veria Yunianingsih.ST)
- http://php.net/manual/en/control-structures.for.php
Introduction to PHP Variables
PHP variable declaration has the following rules:
- A variable declaration begins by using the $ sign.
- PHP variable names can only contain numbers, letters, and underscores (_).
- Variable names can only start with a letter, and the underscore character.
Examples of valid variable names:
$aku, $_aku
Examples of invalid variable names:
$123, $aku+123, $+123
PHP variable declarations are case sensitive, meaning that uppercase and lowercase letters are distinguished. For example, $aku and $Aku are considered by PHP as two different variables.
The following is an example of a PHP variable declaration using a specific data type:
PHP variables of type Integer
$bilangan1 = 123;
$bil_bulat = 345;
$bil3 = 567;
Note that the three variables above all store integers. PHP will assume that the three variables are variables with the integer data type, because the three variables store integers.
PHP variables of type Floating point number or real data type
$bil_real1 = 0.123;
$bil_real2 = 1.858;
$realku = 8.989;
Note that all three variables store fractional or non-whole numbers. PHP will assume that all three variables are real data types, because all three variables store fractional or decimal numbers.
PHP variables of type String
$string1 = "Nasi goreng";
$stringku = "Game ini bagus banget";
$mystring = '123 sayang semuanya';
Pay attention to the three variables. In the three variables, the value of each variable is surrounded by double quotes (") or single quotes ('). PHP will consider the variable to have a string value if the value of the variable is surrounded by single quotes or double quotes.
Note: You cannot combine double quotes(") with single quotes(') to declare PHP variables of type string.
Example:
$mystring = "123'
$stringmy = '321"
The example above is also an invalid variable, because PHP does not allow this.
PHP variables of type Boolean
$benar = TRUE;
$salah = FALSE;
$nol = NULL;
$emptystring1 = '';
$emptystring2 = "";
The two variables above are variables that store the values TRUE, FALSE, NULL, and empty string.
Please note that PHP considers the integer value 0, the real value 0.0, the NULL value, and the empty string as FALSE values.
Remember the word NULL must be written in all capital letters because PHP is a case sensitive programming language, where uppercase and lowercase letters are distinguished.
Reference
Dynamic Web Programming Module (Veria Yunianingsih.ST)
History of PHP
PHP Tools, FI, Construction Kit, and PHP/FI
The definition of PHP has undergone many developments along with the changing times, actually the successor to the product named PHP / FI (Forms Interpreter), this was created in 1994 by Rasmus Lerdorf, the first incarnation of PHP was a simple set of Common Gateway Interface (CGI), binaries were written using the C programming language at that time. Initially used to track visits to online resumes, called the "Personal Home Page Tools" (PHP Tools) script suite.
Over time, the functions included more and more, so Rasmus Lerdorf rewrote PHP Tools, and produced a much larger and richer implementation. This new model is able to interact with databases and much more. Providing a framework above the ordinary user, one of which can develop simple dynamic web applications such as guestbooks.
In June 1995, Rasmus » released the PHP Tools source code to the public, allowing developers to use it as they saw fit. This allowed, and encouraged improvements such as dbugging, so that PHP experienced quite rapid improvement and became more perfect.
In September 1995, Rasmus Lerdorf expanded PHP and in a short time actually dropped the PHP name. Referring to FI (Forms Interpreter), it is a new implementation form including some of the basic functions of PHP as we know it today. These basic functions are Perl variables, Automatic Interpretation of Form Variables, and embedded HTML syntax. The syntax itself is more similar to Perl, although very limited, simple and inconsistent. In fact, to embed HTML code, developers must use HTML comments. Although this method was not fully accepted, FI (Forms Interpreter) continued to enjoy growth and acceptance as a CGI tool, but this was still not enough to make it a new programming language.
In the following month, October 1995, Rasmus Lerdorf re-released the complete source code, thus re-naming PHP as "Personal Home Page Construction Kit", and this release was a proud release for the first time. Considered as an advanced scripting interface (more advanced scripting). This language was deliberately designed to resemble the structure of the C language, making it easier for developers who are familiar with the C or Perl programming languages. After PHP ran well on the UNIX platform and POSIX-complaint systems, the next PHP implementation was explored on the Windows NT platform.
In April 1996, the source code got a complete makeover. This second generation implementation of PHP really started to grow, from being just a tool to becoming a programming language that supports DBM, mSQL, Postgres95 Databases, Cookies, User-defined function support, and much more.
In June 1996, the full PHP/FI package was given the status of "version 2.0". An interesting fact is that when PHP 2.0 was finally declared out of "BETA" status in November 1997, it was confirmed that PHP 2.0 was ready.
Although still in development, PHP's popularity grew rapidly in the young world of web development. In 1997 and 1998, PHP/FI had user survey data of around 60,000 domains, reported that the domains had a header containing "PHP", indicating that the host server had been installed. It is estimated that this number is on the scale of 1% of the total number of websites on the internet.
PHP/FI Code Example
<!--include /text/header.html-->
<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
Hey, you are using Netscape!<p>
<!--endif-->
<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
Sorry, that record does not exist<p>
<!--endif exit-->
Welcome <!--$user-->!<p>
You have <!--$index:0--> credits left in your account.<p>
<!--include /text/footer.html-->
PHP 3
PHP 3.0 is the forerunner of the PHP we currently use.
At that time, it was suspected that PHP/FI 2.0 was still inefficient and could not meet market needs such as eCommerce for example. Andi gutmans and Zeev Suraski from Tel Aviv, Israel, began to develop PHP for their university project, using source code released in 1997.
They approached Rasmus online to discuss various aspects of the implementation that had developed at that time. In an effort to improve the performance of PHP/FI, they (Andi, Zeev and Rasmus) decided to collaborate on the development of a newer and independent programming language. That's when the name 'PHP' was changed to a recursive abbreviation, PHP stands for "PHP Hypertext Preprocessor".
One of the greatest strengths of PHP 3.0 is its features that allow for further development from generation to generation. In addition to being available to end users with mature interfaces for several databases, protocols and APIs, it is also easy to extend the language itself, so that it invites the interest of dozens of developers, their enthusiasm is marked by the variety of modules they offer.
This debate was the key to PHP 3.0's success. Other key success factors included object-oriented programming support and a much more consistent and powerful language syntax.
In June 1998, as more developers from around the world joined, the new PHP Development Team was announced as the Official successor to PHP/FI 2.0.
At the time of the official release of PHP 3.0, at that time the language had been installed on more than 70,000 domains worldwide, and was no longer limited to UNIX or POSIX, but also Windows 95, 98, NT, and Macintosh. At its peak, PHP 3.0 had been installed on around 10% of web servers on the internet.
PHP 4
In the winter of 1998, Andi Gutmans and Zeev Suraski began work on a rewrite of the PHP core, aimed at improving the performance of complex applications, and increasing PHP's modularity, allowing PHP 3.0 to have support for third-party databases and APIs, but PHP 3.0 was not yet designed to handle complex applications efficiently.
The new engine, dubbed "Zend engine" was taken from their names (Zeev and Andi), having the same goal that made its design successful. PHP 4.0 based on Zend Engine was first introduced in 1999, but was officially released in May 2000. Other important features are support for multiple web servers, HTTP sessions, output buffering, security, and several new language constructs.
PHP 5
PHP 5 was released in July 2004 after a long development. The features added in Zend Engine 2.0 are the object model and dozens of other new features.
Dozens of developers and related people, who work to support the PEAR, PECL, documentation, and network infrastructure projects, are the basis for PHP 5 being used on more than 100 web servers worldwide. This analysis is derived from previous statistics.
Some examples of PHP syntax:
<? dan ?>
<?php dan ?>
<script language ="php"> dan </script>
<% dan, %>
Commenting in php
//isi komentar untuk memberikan komentar satu baris
#isi komentar untuk memberikan komentar satu baris
/*isi komentar */ untuk memberikan komentar lebih dari satu baris.
PHP syntax implementation:
PHP scripts act as tags in HTML, the following is an example:
<html>
<head>
<title>Belajar PHP </title>
</head>
<body>
Halo semua, Saya baru belajar PHP...! <br>
<?php
printf("Ternyata mudah belajar PHP");
?>
</body>
</html>
*Save the file with php extension
Example of using PHP comments:
<html>
<head>
<title>Belajar PHP </title>
</head>
<body>
Halo semua, Saya baru belajar PHP...! <br>
<!-- Teks ini dibuat dalam tag HTML -->
<?php
echo("Ternyata mudah belajar PHP");
// Teks ini dibuat dalam tag PHP
# Komentar tidak dicetak dilayar
/* Jika komentar lebih dari satu baris
digunakan tanda ini */
?>
</body>
</html>
Reference:
- http://id1.php.net/manual/en/history.php.php
- Dynamic Web Programming Module (By Ms. Lulu El Rahma)