0% found this document useful (0 votes)
3 views7 pages

IWTunit 5

This document provides an overview of connecting to a MySQL database using PHP, specifically through MySQLi and PDO extensions. It covers essential operations such as creating databases and tables, inserting and selecting data, and managing databases and tables, including deletion. Additionally, it discusses the use of PHPMyAdmin for database administration and common debugging practices in PHP programming.

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

IWTunit 5

This document provides an overview of connecting to a MySQL database using PHP, specifically through MySQLi and PDO extensions. It covers essential operations such as creating databases and tables, inserting and selecting data, and managing databases and tables, including deletion. Additionally, it discusses the use of PHPMyAdmin for database administration and common debugging practices in PHP programming.

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Unit 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 ) {

die('Could not connect: ' . mysqli_error());


Unit 5
}
$sql = 'DROP DATABASE demo';

$retval = mysqli_query( $sql, $link );

if(! $retval ) {

die('Could not delete database demo: ' . mysqli_error());

echo "Database deleted successfully\n";

mysqli_close($link);

?>

DELETING DATA AND TABLES


1. Delete Data : The DELETE statement is used to delete records from a table:
Syntax: DELETE FROM table_name WHERE some_column = some_value
Example:
<?php
$link = mysqli_connect("localhost", "root", "", "demo");
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE FROM MyGuests WHERE first_name='John'";
if(mysqli_query($link, $sql))
{
echo "Records were deleted successfully.";
}
else
{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>

2. Deleting table: Drop statement is used to delete a table.


Syntax: DROP TABLE tablename;
Example:
<?php
$link = mysqli_connect("localhost", "root", "", "demo");
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DROP TABLE MyGuests;
if(mysqli_query($link, $sql))
Unit 5
{
echo "Records were deleted successfully.";
}
else
{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>

PHP MYADMIN AND DATA BASEBUGS


MY ADMIN PhpMyAdmin is a LAMP application that is written in PHP. Its specific purpose is to enable users
with the ability to interact with and administer MySQL servers. All the information of WordPress is collected in
the MySQL database, which is then coordinated with the database to create information in the WordPress
site. phpMyAdmin offers a graphical interface of the data, tables and fields stored in the MySQL database for
database administration tasks.
PHPmyadmin Interface
The Prime Features of PHPmyadmin
• Insightful web interface
• Support for almost all MySQL features including SQL-statement execution, editing
and bookmarking, Housed procedures and triggers management, databases, tables,
fields and indexes management and MySQL users and privileges management.
• Data import from CSV and SQL
• Multiple servers administration
• Generating queries via Query-by-example (QBE)
• Searching worldwide in a database or a subset of it
• Generating PDF graphics of your database design
DATABASEBUGS
PHP defines some constants you can use to set the value of error_reporting such that only errors of certain
types get reported:
E_ALL (for all errors except strict notices),
E_PARSE (parse errors), E_ERROR (fatal errors),
E_WARNING (warnings), E_NOTICE (notices), and E_STRICT (strict notices).
While writing your PHP program, it is a good idea to use PHP-aware editors like
BBEdit or Emacs.
One of the special features of these editors is syntax highlighting.
It changes the color of different parts of your program based on what those parts are.
For example, strings are pink, keywords such as if and while are blue, comments are grey, and
variables are black.
Another feature is quote and bracket matching, which helps to make sure that your quotes
and brackets are balanced. When you type a closing delimiter such as}, the editor highlights
the opening {that it matches.
There are following points which need to be verified while debugging your program.
• Missing Semicolons − Every PHP statement ends with a semicolon (;). PHP doesn't stop reading a statement
until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the
statement on the following line.
• Not Enough Equal Signs − When you ask whether two values are equal in a comparison statement, you need
two equal signs (==). Using one equal sign is a common mistake.
Unit 5
• Misspelled Variable Names − If you misspelled a variable then PHP understands it as a new variable.
Remember: To PHP, $test is not the same variable as $Test.
• Missing Dollar Signs − A missing dollar sign in a variable name is really hard to see, but at least it usually
results in an error message so that you know where to look for the problem.
• Troubling Quotes − You can have too many, too few, or the wrong kind of quotes. So check for a balanced
number of quotes.
• Missing Parentheses and curly brackets − They should always be in pairs.
• Array Index − All the arrays should start from zero instead of 1. Moreover, handle all the errors properly and
direct all trace messages into system log file so that if any problem happens then it will be logged into system
log file and you will be able to debug that problem

You might also like