Download lec#7 mysql - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Relational algebra wikipedia , lookup

IMDb wikipedia , lookup

Microsoft Access wikipedia , lookup

Oracle Database wikipedia , lookup

Concurrency control wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Functional Database Model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Database wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Versant Object Database wikipedia , lookup

Clusterpoint wikipedia , lookup

SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

PL/SQL wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
LEC#7 INTRODUCTION TO MYSQL
What is MySQL
MySQL is one of the most popular relational database system being used on the
Web today. It is freely available and easy to install, however if you have
installed Wampserver it already there on your machine. MySQL database server
offers several advantages:

MySQL is easy to use, yet

MySQL runs on a wide range of operating systems, including UNIX, Microsoft
Windows, Apple Mac OS X, and others.

MySQL supports standard SQL (Structured Query Language).

MySQL is ideal database solution for both small and large applications.

MySQL is developed, and distributed by Oracle Corporation.

MySQL is very fast and secure. It includes data security layers that protect
sensitive data from intruders.
powerful, secure, and scalable.
MySQL database stores data into tables like other relational database. A table is
a collection of related data, and it is divided into rows and columns.
Each row in a table represents a data record that are inherently connected to
each other such as information related to a particular person, whereas each
column represents a specific field such as 'first_name', 'last_name',
'email_address', etc. The structure of a simple MySQL table that contains
person's general information may look something like this:
+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address
|
+-----------+------------+-----------+----------------------+
|
1 | Peter
| Parker | [email protected] |
|
2 | John
| Rambo
|
3 | Clark
| Kent
|
4 | John
| Carter | [email protected] |
| [email protected] |
| [email protected] |
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 1
LEC#7 INTRODUCTION TO MYSQL
|
5 | Harry
| Potter | [email protected] |
+-----------+------------+-----------+----------------------+
Talking to MySQL Databases with SQL
SQL, the Structured Query Language, is a simple, standardized language for
communicating with relational databases like MySQL. With SQL you can
perform any database-related task, such as creating databases and tables, saving
data in database tables, query a database for specific records, deleting and
updating data in databases.
Look at the following standard SQL query that returns the email address of a
person whose first name is equal to 'Peter' in the persons table:
SELECT email_address FROM persons WHERE first_name="Peter"
Open a Connection to MySQL Database Server
In order to access the data inside a MySQL database, you first need to open a
connection to the MySQL database server. In PHP you can easily do this using
the mysqli_connect()function. All communication between PHP and the
MySQL database server takes place through this connection. The basic syntax
of the mysqli_connect() function is given with:
mysqli_connect(host, username, password, dbname);
The parameters in the above syntax have the following meanings:
Parameter
Description
Optional — All the parameters are optional
host
Either a host name or an IP address
username
The MySQL user name
password
The MySQL password to get access
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 2
LEC#7 INTRODUCTION TO MYSQL
Parameter
Description
dbname
The name of the MySQL database to use
The example below shows the mysqli_connect() function in action.
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "");


// Check connection

if($link === false){

die("ERROR: Could not connect. " . mysqli_connect_error());

}

?>
Note:The default username for MySQL database server is 'root' and there is no
password. However to prevent your databases from intrusion and unauthorized
access you should set password for MySQL accounts.
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 3
LEC#7 INTRODUCTION TO MYSQL
Closing the MySQL Database Server Connection
The connection to the MySQL database server will be closed automatically as
soon as the execution of the script ends. However, if you want to close it earlier
you can do this by simply calling the PHP mysql_close() function.
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Close connection

mysqli_close($link);

?>
Creating Database and Tables Using PHP and MySQL
Now that you've understood how to open a connection to the MySQL database
server. In this tutorial you will learn how to execute SQL query to create a
database and tables.
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 4
LEC#7 INTRODUCTION TO MYSQL
Creating the MySQL Database
Since all tables are stored in a database, so first we have to create a database
before creating tables. The CREATE DATABASE statement is used to create a
database in MySQL.
Let's make a SQL query using the CREATE DATABASE statement, after that
we will execute this SQL query through passing it to
the mysqli_query() function to finally create our database. The following
example creates a database named "demo".
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Attempt create database query execution

$sql = "CREATE DATABASE demo";

if(mysqli_query($link, $sql)){


echo "Database demo created successfully";
} else{


echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 5
LEC#7 INTRODUCTION TO MYSQL


// Close connection

mysqli_close($link);

?>
Adding Tables to MySQL Database
Since our database is created now it's time to add some tables to it.
The CREATE TABLEstatement is used to create a table in MySQL database.
So let's make a SQL query using the CREATE TABLE statement, after that we
will execute this SQL query through passing it to the mysqli_query() function to
finally create our table.
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "", "demo");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Attempt create table query execution
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 6
LEC#7 INTRODUCTION TO MYSQL

$sql = "CREATE TABLE persons(person_id INT(4) NOT NULL PRIMARY
KEY AUTO_INCREMENT, first_name CHAR(30) NOT NULL, last_name
CHAR(30) NOT NULL, email_address VARCHAR(50))";

if (mysqli_query($link, $sql)){


echo "Table persons created successfully";
} else {


echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


// Close connection

mysqli_close($link);

?>
The PHP code in the above example creates a table named persons which has
four fields 'person_id', 'first_name', 'last_name' and 'email_address'. Notice that
each field name is followed by a data type declaration; this declaration identifies
what type of data the field can hold, whether string, numeric, temporal, or
Boolean. MySQL supports a number of different data types, the most important
ones are summarized below.
Field Type
Description
INT
A numeric type that can accept values in the range of -2147483648
to 2147483647
DECIMAL
A numeric type with support for floating-point or decimal numbers
CHAR
A string type with a maximum size of 255 characters and a fixed
length
VARCHAR A string type with a maximum size of 255 characters and a
variable length
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 7
LEC#7 INTRODUCTION TO MYSQL
Field Type
Description
TEXT
A string type with a maximum size of 65535 characters
DATE
A date field in the YYYY-MM-DD format
TIME
A time field in the HH:MM:SS format
DATETIME A combined date/time type in the YYYY-MM-DD HH:MM:SS
format
Not Null, Primary Key and Auto Increment Fields
There are a few additional modifiers that are specified after the fields in the
preceding SQL statement like: NOT NULL, PRIMARY KEY,
AUTO_INCREMENT. It has the following meaning

The NOT NULL modifier definition specifies that the field cannot accept a
NULL value.

The PRIMARY KEY modifier marks the corresponding field as the table's
primary key which is used to uniquely identify the rows in a table. Each table in
a relational database should have a primary key field.

The AUTO_INCREMENT modifier tells MySQL to automatically generate a
value for this field every time a new record is inserted into the table, by
incrementing the previous value by 1. Only available for numeric fields.
In the upcoming chapters you will learn how to insert new records as well as
how to update, delete and view the existing records of persons table inside the
demo database.
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 8
LEC#7 INTRODUCTION TO MYSQL
Inserting Data Into a MySQL Database Table
Now that you've understood how to create database and tables in MySQL. In
this tutorial you will learn how to execute SQL query to insert records in a table.
Let's make a SQL query using the INSERT INTO statement with appropriate
values, after that we will execute this SQL query through passing it to the
mysqli_query() function to insert data in table. Here's an example, which adds a
record to the persons table by specifying values for the 'person_id', 'first_name',
'last_name' and 'email_address' fields:
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "", "demo");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Attempt insert query execution

$sql = "INSERT INTO persons (person_id, first_name, last_name,
email_address) VALUES (1, 'Peter', 'Parker', '[email protected]')";

if(mysqli_query($link, $sql)){



echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 9
LEC#7 INTRODUCTION TO MYSQL

}


// Close connection

mysqli_close($link);

?>
If you remember, from the preceding section, the 'person_id' field was marked
with the AUTO_INCREMENT flag. This modifier tells the MySQL to
automatically assign a value to this field if it is left unspecified while inserting a
new record to the persons table. To see this in action, try adding another record
using the following statement:
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "", "demo");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Attempt insert query execution

$sql = "INSERT INTO persons (first_name, last_name, email_address)
VALUES ('John', 'Rambo', '[email protected]')";

if(mysqli_query($link, $sql)){

echo "Records added successfully.";
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 10
LEC#7 INTRODUCTION TO MYSQL

} else{


echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


// Close connection

mysqli_close($link);

?>
Now go the phpMyAdmin (http://localhost/phpmyadmin/) and check out the
persons table data inside the demo database, you will see the new 'person_id' is
assigned automatically by incrementing the value of previous 'person_id' by 1.
Insert Data Into a Database From an HTML Form
Let's create an HTML form that can be used to insert new records to persons
table.
Creating the HTML Form
Here's a simple HTML form that has three text <input> fileds and a submit
button.
Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Add Record Form</title>

</head>

<body>
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 11
LEC#7 INTRODUCTION TO MYSQL


<form action="insert.php" method="post">
<p>

<label for="firstName">First Name:</label>

<input type="text" name="firstname" id="firstName">

</p>

<p>

<label for="lastName">Last Name:</label>

<input type="text" name="lastname" id="lastName">

</p>

<p>

<label for="emailAddress">Email Address:</label>

<input type="text" name="email" id="emailAddress">

</p>

<input type="submit" value="Submit">

</form>

</body>

</html>
Retrieving and Inserting the Form Data
When a user clicks the submit button of the add record HTML form, in the
example above, the form data is sent to 'insert.php' file. The 'insert.php' file
connects to the MySQL database server, retrieves forms fields using the
PHP $_POST variables and finally execute the insert query to add the records.
Here is the complete code of our 'insert.php' file:
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 12
LEC#7 INTRODUCTION TO MYSQL
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "", "demo");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Escape user inputs for security

$first_name = mysqli_real_escape_string($link, $_POST['firstname']);

$last_name = mysqli_real_escape_string($link, $_POST['lastname']);

$email_address = mysqli_real_escape_string($link, $_POST['email']);


// attempt insert query execution

$sql = "INSERT INTO persons (first_name, last_name, email_address)
VALUES ('$first_name', '$last_name', '$email_address')";

if(mysqli_query($link, $sql)){


echo "Records added successfully.";
} else{


echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

INTRODUCTION TO MYSQL USING WAMPSERVER
Page 13
LEC#7 INTRODUCTION TO MYSQL

// close connection

mysqli_close($link);

?>
Note:The mysqli_real_escape_string() function escapes special characters in a
string and create a legal SQL string to provide security against SQL injection.
This is very basic example of inserting the form data in a MySQL database
table. You can extend this example and make it more interactive by adding
validations to the user inputs before inserting it to the database tables. Please
check out the tutorial on PHP form validation to learn more about sanitizing and
validating user inputs using PHP.
Selecting Data From Database Tables
So far you have learnt how to create database and table as well as inserting
data. Now it's time to retrieve data what have inserted in the preceding
tutorial.
Let's make a SQL query using the SELECT statement, after that we will
execute this SQL query through passing it to the mysqli_query() function
to retrieve the table data.
The basic syntax of the SELECT query can be given with:
SELECT column_name(s) FROM table_name
Let's make a SQL query using the SELECT statement, after that we will execute
this SQL query through passing it to the mysqli_query() function to select the
tables records. Consider the following "persons" table inside the "demo"
database:
+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address
|
+-----------+------------+-----------+----------------------+
|
1 | Peter
| Parker | [email protected] |
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 14
LEC#7 INTRODUCTION TO MYSQL
|
2 | John
| Rambo
| [email protected] |
|
3 | Clark
| Kent
|
4 | John
| Carter | [email protected] |
|
5 | Harry
| Potter | [email protected] |
| [email protected] |
+-----------+------------+-----------+----------------------+
The PHP code in the following example selects all the data stored in the
"persons" table (using the asterisk character (*) in place of column name selects
all the data in the table).
Example

<?php

/* Attempt MySQL server connection. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

$link = mysqli_connect("localhost", "root", "", "demo");


// Check connection

if($link === false){


die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Attempt select query execution

$sql = "SELECT * FROM persons";

if($result = mysqli_query($link, $sql)){

if(mysqli_num_rows($result) > 0){


echo "<table>";
echo "<tr>";
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 15
LEC#7 INTRODUCTION TO MYSQL

echo "<th>person_id</th>";

echo "<th>first_name</th>";

echo "<th>last_name</th>";

echo "<th>email_address</th>";

echo "</tr>";

while($row = mysqli_fetch_array($result)){

echo "<tr>";

echo "<td>" . $row['person_id'] . "</td>";

echo "<td>" . $row['first_name'] . "</td>";

echo "<td>" . $row['last_name'] . "</td>";

echo "<td>" . $row['email_address'] . "</td>";

echo "</tr>";

}

echo "</table>";

// Close result set

mysqli_free_result($result);

} else{

echo "No records matching your query were found.";

}

} else{


echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


// Close connection
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 16
LEC#7 INTRODUCTION TO MYSQL

mysqli_close($link);

?>
In the example above, the data returned by the mysqli_query() function is stored
in the$result variable. Each time mysqli_fetch_array() is invoked, it returns the
next record from the result set as an array. The while loop is used to loops
through all the records in the result set. Finally the value of individual fields can
be accessed from the record either through passing the field index or the field
name
to
the $row variable
like$row['person_id'] or $row[0], $row['first_name'] or $row[1], $row['last_nam
e'] or$row[2], and $row['email_address'] or $row[3].
If you want to use the for loop you can obtain the loop counter value or the
number of rows returned by the query by passing the $result variable to
the mysqli_num_rows() function. This loop counter value determines how many
times the loop should run.
INTRODUCTION TO MYSQL USING WAMPSERVER
Page 17