Open A Connection To Mysql
Open A Connection To Mysql
Before we can access data in the MySQL database, we need to be able to connect to
the server:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysql($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Close the Connection
$conn->close();
Create a MySQL Database Using MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysql($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
PHP Create MySQL Tables
• A database table has its own unique name and consists of
columns and rows.
• Create a MySQL Table
create a table named "MyGuests", with five columns: "id",
"firstname", "lastname", "email" and "reg_date":
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
)
Example
<?php
$servername = "localhost";
$username = "username";
$password = "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),
reg_date TIMESTAMP
)“;
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
PHP Insert Data Into MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysql($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Upload image in Php
Three Steps need to upload image.
• Make a HTML form to upload the image
• Connect to the database and store image
• Displaying the Image
Step 1.Make a HTML form
• We make a HTML form with post method and
save it with a name upload.html
Upload image in Php
<html>
<body>
<form method="POST" action="getdata.php"
enctype="multipart/form-data">
<input type="file" name="myimage">
<input type="submit" name="submit_image"
value="Upload">
</form>
</body>
</html>
We submit the data from this HTML form to getdata.php
where the image is going to store in the database.
Upload image in Php
Step 2.Connect To Database and Store Image
In this step we have to connect to the database to store the image in
database. You can connect to any database from which you want
to get the data. In this we use sample database named " demo ".
<?php
$host = 'localhost';
$user = 'root';
$pass = ' ';
mysql_connect($host, $user, $pass);
mysql_select_db('demo');
?>
Upload image in Php
To store the image into database you have to
use blob datatype of your image column in
your table. MySQL uses BLOB to store binary
data and images is also a binary data. You can
use any kind of BLOB TINYBLOB, BLOB,
MEDIUMBLOB, LONGBLOB as per the size of
your image.You may also like upload image
from URL using PHP.
Upload image in Php
<?php
$imagename=$_FILES["myimage"]["name"];
mysql_query($insert_image);
?>
When a file is uploaded, it gets stored in a temporary area on the server until it is
moved. The file has to be moved from that area, or else it will be destroyed. In the
meantime, the $_FILES[] superglobal array is filled up with data about the uploaded file.
Since the file's upload field in our example is called "my-file", the following data is
created:
Upload image in Php
Step 3.Displaying the stored Images from
database
To display images you have to make two files
one is to fetch the image from database and
second one is to display the image. You may
also like upload multiple images with preview
using jQuery and PHP.
This is fetch_image.php file
Upload image in Php
<?php
header("content-type:image/jpeg");
$host = 'localhost';
$user = 'root';
$pass = ' ';
mysql_connect($host, $user, $pass);
mysql_select_db('demo');
$name=$_GET['name'];
$select_image="select * from image_table where imagename= '$name'";
$var=mysql_query($select_image);
if($row=mysql_fetch_array($var))
{ $image_name=$row["imagename"]; $image_content=$row["imagecontent"];
}
echo $image;
?>
Upload image in Php
Now we want to display the image we make another file display_image.php.
<html>
<body>
<form method="GET" action=" " >
<input type="file" name="your_imagename">
<input type="submit" name="display_image" value="Display">
</form>
</body>
</html>
<?php
$getname = $_GET[' your_imagename '];
echo "< img src = fetch_image.php?name=".$getname." width=200 height=200 >";
?>
Cookie
• A cookie is often used to identify a user.
• A cookie is a small file (4kb) that the server
embeds on the user’s computer.
• Each time the same computer requests a page
with a browser, it will send the cookie too.
• Each time the browser requests a page to the
server, all the data in the cookie is automatically
sent to the server within the request.
cookie
• whenever the browser requests a page on
your Web site, all the data in the cookie is
automatically sent to the server within the
request.
• This means that you can send the data once to
the browser, and the data is automatically
available to your script from that moment
onward.
cookie
• You can make a cookie last for a fixed amount
of time — anywhere from a few seconds to
several years
• if you like — or you can set a cookie to expire
once the browser application is closed. Most
modern browsers can store up to 30 cookies
per Web site domain.
There are three steps involved in identifying returning users
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
•The following example creates a small script that checks whether cookies are enabled. First, try to create a
test cookie with the setcookie() function, then count the $_COOKIE array variable:
•Example
•<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Output:
Cookies are enabled.
Session
• Although cookies are a useful way to store data, they have a couple
of problems.
• First of all, they aren ’ t very secure. As with form data and query
strings, an attacker can easily modify a cookie ’ s contents to insert
data that could potentially break your application or compromise
security.
• Secondly, although you can store a fair amount of state information
in a cookie, remember that all the cookie data for a Web site is sent
every time the browser requests a URL on the server.
• If you have stored 10 cookies, each 4KB in size, on the browser,
then the browser needs to upload 40KB of data each time the user
views a page!
Session
• Both of these issues can be overcome by using PHP
sessions.
• Rather than storing data in the browser, a PHP session
stores data on the server, and associates a short session ID
string (known as SID) with that data.
• The PHP engine then sends a cookie containing the SID to
the browser to store.
• Then, when the browser requests a URL on the Web site, it
sends the SID cookie back to the server, allowing PHP to
retrieve the session data and make it accessible to your
script.
Session
• The session IDs generated by PHP are unique, random, and almost
impossible to guess, making it very hard for an attacker to access or
change the session data.
• Furthermore, because the session data is stored on the server, it
doesn ’ t have to be sent with each browser request. This allows you
to store a lot more data in a session than you can in a cookie.
• By default, PHP stores each session ’ s data in a temporary file on
the server.
• The location of the temporary files are specified by the
Session.save_path directive in the PHP configuration file.
• You can display this value with:
echo ini_get( “session.save_path” );
Sessions
• 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.
• If you need a permanent storage, you may want to store the data in a
database.
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 "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
• Example
• <?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.
• The session_start() function must be the very first thing in your document. Before any HTML
tags.
Get PHP Session Variable Values
<?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>
Output:
Favorite color is .
Favorite animal is .
Get PHP Session Variable Values
• Another way 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>
• Output:
• Array ( [favcolor] => green [favanimal] => cat )
Modify a PHP Session Variable
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
• Output:
• Array ( [favcolor] => yellow )