IWTunit 5
IWTunit 5
CONNECTION TO 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. Here're the basic syntaxes for connecting to
MySQL using MySQLi and PDO extensions:
Syntax: MySQLi, Procedural way
$link = mysqli_connect("hostname", "username", "password", "database");
Syntax: MySQLi, Object Oriented way
$mysqli = new mysqli("hostname", "username", "password", "database");
Syntax: PHP Data Objects (PDO) way
$pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password");
The hostname parameter in the above syntax specify the host name (e.g. localhost), or IP address of the
MySQL server, whereas the username and password parameters specifies the credentials to access MySQL
server, and the database parameter, if provided will specify the default MySQL database to be used when
performing queries.
Example: Attempt MySQL server connection. Assuming you are running MySQL server with default
setting (user 'root' with no password)
<?php
$link = mysqli_connect("localhost", "root", ""); // Check connection
if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
CREATE DATABASE
In this statement, after that we will execute this SQL query through passing it to the PHP mysqli_query()
function to finally create our database. CREATE DATABASE DatabaseName";
Example:
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
{ die("ERROR: Could not connect. ".mysqli_connect_error()); }
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){ echo "Database created successfully"; }
else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link); ?>
CREATING A TABLE
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" and
"reg_date":
Syntax: CREATE TABLE tablename(colname datatype constraints,……);
<?php
$link = mysqli_connect("localhost", "root","","demo");
if($link === false)
{
die("ERROR: Could not connect.".mysqli_connect_error());
}
else
{
Unit 5
echo "Connect Successfully.Hostinfo:".mysqli_get_host_info($link);
}
$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 DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP)";
if(mysqli_query($link, $sql))
{
echo "Table MyGuests created successfully";
}
else
{
echo "Error creating table:".mysqli_error($link);
}
mysqli_close($link);
?>
Notes on the table above:
The data type specifies what type of data the column can hold. After the data type, you can specify other
optional attributes for each column:
• 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
INSERTING DATA
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
<?php
$link = mysqli_connect("localhost", "root","","demo");
if($link === false)
{
die("ERROR: Could not connect.".mysqli_connect_error());
}
else
{
echo "Connect Successfully.Hostinfo:".mysqli_get_host_info($link);
}
$sql= "INSERT INTO MyGuests (firstname, lastname, email)
Unit 5
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
mysqli_close($link);
?>
SELECT Data
this statement is used to select the records from database tables. Its basic syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;
<?php
$link = mysqli_connect("localhost", "root","","demo");
if($link === false)
{
die("ERROR: Could not connect.".mysqli_connect_error());
}
else
{
echo "Connect Successfully.Hostinfo:".mysqli_get_host_info($link);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($link);
?>
LISTING DATABASES
Using the above query we will develop a PHP PDO script to display all the databases present. Here is the code:
<?Php
$dbo=new PDO("mysql:host=localhost;dbname=demo", "root", "");
$result = $dbo->query("SHOW DATABASES");
while ($row = $result->fetch(PDO::FETCH_NUM))
{
echo $row[0]."<br>"; }
Unit 5
?>
LISTING TABLE NAMES
1. We connect to MySQL using the PDO object. In this particular example, I am using the database “test”.
2. We create our SQL statement, which is “SHOW TABLES”. This SQL statement tells MySQL to return a list of
the tables that exist in our currently- selected database.
3. We prepare the SQL statement.
4. We execute the SQL statement.
5. We fetch the results using fetchAll.
6. Finally, we loop through the results and print out the name of each table.
<?Php
$dbo=new PDO("mysql:host=localhost;dbname=dbase", "root", "");
$result=$dbo->query("SHOW TABLES");
while($row=$result->fetch(PDO::FETCH_NUM))
{
echo $row[0]."<br>"; }
?>
ALTERING TABLES
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype;
Example
ALTER TABLE Customers ADD Email varchar(255);
QUERIES
The mysqli_query() function performs a query against the database.
mysqli_query(connection,query,resultmode);
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
else
{
//Query Statement;
}
mysqli_close($con); ?>
DELETING DATABASE
If a database is no longer required then it can be deleted forever. You can use pass an SQL command
to mysqli_query to delete a database.
<?php
$link = mysqli_connect(“localhost”,”root”,””);
if(!$link ) {
if(! $retval ) {
mysqli_close($link);
?>