You are on page 1of 32

Connect PHP to MySQL

What is MySQL?
 MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP.
 Structured Query Language (SQL). The data in a MySQL database are stored in tables that consist
of columns and rows.
 MySQL is a database system that runs on a server. MySQL is ideal for both small and large
applications. MySQL is a very fast, reliable, and easy-to-use database system. It uses standard
SQL. MySQL compiles on a number of platforms.
How we can connect PHP to MySQL?
 PHP 5 and later can work with a MySQL database using:
 MySQLi extension (the ‘i’ is abbreviation for improved)
 PDO (PHP Data Objects)
Which one should we use MySQLi or PDO?
 Both MySQLi and PDO have their recompenses:
 PDO will work with 12 different database systems, whereas MySQLi will only work with MySQL
databases.
 So, if you have to shift your project to use alternative database, PDO makes the process easy. You
only have to change the connection string and a few queries. With MySQLi, you will need to
rewrite the complete code — queries included.
 Both are object-oriented, but MySQLi also offers a procedural API.
connection to MySQL using MySQLi
PHP provides mysql_connect() function to open a database connection.
This function takes a single parameter, which is a connection returned by the
mysql_connect() function.
You can disconnect from the MySQL database anytime using another PHP function
mysql_close().
There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP
script.
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = new mysqli($servername,
$username, $password);
// For checking if connection is
// successful or not
if ($conn->connect_error) {
die("Connection failed: "
. $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = mysqli_connect($servername,
$username, $password);
// Check if connection is Successful or not
if (!$conn) {
die("Connection failed: "
. mysqli_connect_error());
}
echo "Connected successfully";
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Connection
$conn =mysqli_connect($servername,$username,$password );
// For checking if connection is successful or not
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
PHP Create a MySQL Database
<?php
$servername = "localhost";
$username = “root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Create a MySQL Table Using MySQLi
The CREATE TABLE statement is used to create a table in MySQL.
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email“.
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)
• NOT NULL - Each row must contain a value for that column, null values are not allowed
• DEFAULT value - Set a default value that is added when no other value is passed
• UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a
new record is added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY
setting is often an ID number, and is often used with AUTO_INCREMENT
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>
<body>
<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="contact.php">
<p>
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
</p>
<p>
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
</p>
<p>&nbsp;</p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset></body></html>
<?php
print_r($_POST);
$con = mysqli_connect('localhost', 'root', '','db_contact');
echo "conection sucessfully";
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];
echo "variables created";
$sql = "INSERT INTO tbl_contact (fldName, fldEmail, fldPhone, fldMessage) VALUES
('$txtName', '$txtEmail', '$txtPhone','$txtMessage')";
$con->query($sql);
echo "record inserted";
?>
What is a Cookie
 A cookie is an item of data that a web server saves to your computer’s hard disk via a web
browser.
 It can contain almost any alphanumeric information (as long as it’s under 4 KB) and can be
retrieved from your computer and returned to the server.
 Common uses include session tracking, maintaining data across multiple visits, holding shopping
cart contents, storing login details, and more.
 Because of their privacy implications, cookies can be read only from the issuing domain.
 In other words, if a cookie is issued by, for example, oreilly.com, it can be retrieved only by a web
server using that domain. This prevents other websites from gaining access to details for which
they are not authorized.
 Because of the way the Internet works, multiple elements on a web page can be embedded from
multiple domains, each of which can issue its own cookies. When this happens, they are referred
to as third-party cookies. Most commonly, these are created by advertising companies in order to
track users across multiple websites.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
PHP Create/Retrieve a Cookie
• The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
• We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
The setcookie() function must appear BEFORE the <html> tag.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php

if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Modify a Cookie Value
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
• To delete a cookie, use the setcookie() function with an expiration date in the past:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
PHP Session
 PHP session is used to store and pass information from one page to another temporarily (until user
close the website).sessions are stored in server side
 A session is a way to store information (in variables) to be used across multiple pages.
 Unlike a cookie, the information is not stored on the users computer.
 When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
 Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
 So; Session variables hold information about one single user, and are available to all pages in one
application.
Start a PHP Session
 A session is started with the session_start() function.
 Session variables are set with the PHP global variable: $_SESSION.
 Now, let's create a new page called “session.php". In this page, we start a new PHP session and set
some session variables:
 The session_start() function must be the very first thing in your document. Before any HTML tags.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Output:
Session variables are set.
Get PHP Session Variable Values
 Next, we create another page called "demo_session2.php". From this page, we will access the session
information we set on the first page ("demo_session1.php").
 Notice that session variables are not passed individually to each new page, instead they are retrieved from the
session we open at the beginning of each page (session_start()).
 Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
To show all the session variable values for a user session is to run the following code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Modify a PHP Session Variable
To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the session, use session_unset() and session_destroy():
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
Working with directories:
• getcwd( ):The full form of getcwd is "Get Current Working Directory", the function getcwd() is used to
get the name of the current working directory, it does not accept any parameter and returns the current
working directory.
Syntax:
getcwd();
• It does not accept any parameter.
• Example: PHP code to get the name of the current working directory
Example:
<?php
$result = getcwd();
echo "current working directory is: ".$result."<br/>";
?>
Output:
current working directory is: C:\xampp\htdocs\amrutha
mkdir() :
The full form of mkdir is "Make Directory", the function mkdir() is used to create a directory.
Syntax:
mkdir(dir_path, access_mode, recursive, context);
Example:
<?php
$result = mkdir("c:/xampp/htdocs/amrutha/folder1");
if($result==true)
echo"directory created successfully";
else
echo "directory is not created";
?>
Output:
directory created successfully
chdir():
• The full form of chdir is "Change Directory", the function chdir() is used to change the current working
directory.
Syntax:
mkdir(directory);
directory – It defines the new directory.
Example:
<?php
$result=getcwd();
echo "current working directory is: ".$result."<br/>";
chdir("c:/xampp/htdocs/amrutha/folder1");
$result=getcwd();
echo "current working directory is: ".$result."<br/>";
?>
Output:
Current working directory is:C:\xampp\htdocs\amrutha
current working directory is: C:\xampp\htdocs\amrutha\folder1
is_dir():
The full form of is_dir is "Is Directory", the function is_dir() is used to check whether a file system is a
directory or whether a directory exists or not.
Syntax:
is_dir(directory);
Example: PHP code to check whether a directory exists or not
<?php mkdir("c:/xampp/htdocs/amrutha/folder2");
if(is_dir("c:/xampp/htdocs/amrutha/folder2"))
echo"this folder is exists";
else
echo "folder is not exists";
?>
Output:
this folder is exists
scandir():
The full form of scandir is "Scan Directory", the function scandir() is used to get the list of the files and
directories available in the specified directory.
Syntax:
scandir(directory, sorting_order, context);
Parameter(s):
• directory – It specifies the directory name (or path) from there we have to get the list of the files and
directories
• sorting – It is an optional parameter; its default value is o (alphabetically sorting order). 1 can be used to
descending order.
• context – It is an optional parameter; it is used to specify the context (a set of options that can modify the
behavior of the stream) to the directory handle.
Example:
<?php
$path=“C:/";
$arr1=scandir($path);
print_r($arr1);
?>
rmdir():It is used to remove directory or folder.

Syntax:
rmdir(directory);

Example:
<?php
$path="c:/xampp/htdocs/amrutha/folder1";
rmdir($path);
?>

You might also like