Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Open A Connection To Mysql

The document provides information on connecting to a MySQL database, creating a database and tables, inserting data, and uploading images using PHP. It discusses opening a connection, creating a database, creating tables with columns and data types, inserting data into tables, and uploading images by making an HTML form, connecting to the database, storing images in BLOB fields, and displaying the images.

Uploaded by

Deepak Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Open A Connection To Mysql

The document provides information on connecting to a MySQL database, creating a database and tables, inserting data, and uploading images using PHP. It discusses opening a connection, creating a database, creating tables with columns and data types, inserting data into tables, and uploading images by making an HTML form, connecting to the database, storing images in BLOB fields, and displaying the images.

Uploaded by

Deepak Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

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);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->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"];

//Get the content of the image and then add slashes to it


$imagetmp=addslashes (file_get_contents($_FILES['myimage']
['tmp_name']));

//Insert the image name and image content in image_table


$insert_image="INSERT INTO image_table
VALUES('$imagetmp','$imagename')";

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

• Server script sends a set of cookies to the


browser. For example name, age, or
identification number etc.
• Browser stores this information on local
machine for future use.
• When next time browser sends any request to
web server then it sends those cookies
information to the server and server uses that
information to identify the user.
Create Cookies With PHP

A cookie is created with the setcookie() function.


Syntax
setcookie(name, value, expire, path, domain,
secure, httponly);
Only the name parameter is required. All other
parameters are optional.
Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information
since this value is stored on the user's computer.
Expires The expiry date in UNIX timestamp format. After this time
cookie will become inaccessible. The default value is 0.
path Specify the path on the server for which the cookie will
be available. If set to /, the cookie will be available within the
entire domain.
domain Specify the domain for which the cookie is available to
e.g www.example.com.
secure This field, if present, indicates that the cookie should be sent
only if a secure HTTPS connection exists.
HttpOnly : This field, if present, tells the
browser that it should make the cookie data
accessible only to scripts that run on the Web
server (that is, via HTTP). Attempts to access
the cookie via JavaScript within the Web page
are rejected.
example
<?php
// Setting a cookie
setcookie("username", "John Carter", time()
+30*24*60*60);
?>
create a cookie named username and assign the
value value John Carter to it. It also specify that
the cookie will expire after 30 days (30 days * 24
hours * 60 min * 60 sec).
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to
retrieve a cookie value. It typically an array that
contains a list of all the cookies values sent by the
browser in the current request, keyed by cookie name.
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
Output : John Carter
Check cookie set or not
• It's a good practice to check whether a cookie is set or not
before accessing its value. To do this you can use the PHP isset()
function, like this:
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
Location of cookie
C:\Users\username\AppData\Roaming\Microsof
t\Windows\Cookies
Modify a cookie value
• To modify a cookie, just set the cookie using
the setcookie() function.
• setcookie($cookie_name, cookie_value);
Eg. Cookie 'user' is set!
Value is: John Doe
• Reload the page
• Cookie 'user' is set!
Value is: Alex Porter
Delete a Cookie

• Deleting a cookie is very simple.


• You don't have to specify a cookie value when you delete a cookie.
• Just set the expires parameter to a passed date:
• <?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?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

• 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:
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

• To change a session variable, just overwrite it:


• Example
• <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>
• Output:
• Array ( [favcolor] => yellow )

You might also like