0% found this document useful (0 votes)
3 views

web programming lecture 6

The document provides an overview of managing data using PHP and MySQL, highlighting MySQL as a fast and reliable database system suitable for various applications. It covers key concepts such as database queries, MySQL functions, and the improved MySQLi extension, along with practical examples of connecting to a database, creating databases and tables, and inserting data. The document serves as a guide for developers to effectively utilize PHP in conjunction with MySQL for database management.

Uploaded by

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

web programming lecture 6

The document provides an overview of managing data using PHP and MySQL, highlighting MySQL as a fast and reliable database system suitable for various applications. It covers key concepts such as database queries, MySQL functions, and the improved MySQLi extension, along with practical examples of connecting to a database, creating databases and tables, and inserting data. The document serves as a guide for developers to effectively utilize PHP in conjunction with MySQL for database management.

Uploaded by

ihhridoy000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Managing Data with PHP and MySQL

Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

What is MySQL?

 MySQL is a database system used on the web


 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of


related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may have
a database with the following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL Database System


 PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)

With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

Database Queries
A query is a question or a request.

We can query a database for specific information and have a recordset


returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the
"Employees" table.

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

MySQL Functions

These functions allow you to access MySQL database servers. More information about MySQL
can be found at http://www.mysql.com/.

Documentation for MySQL can be found at http://dev.mysql.com/doc/.

Detail list of Functions are as follows

Table of Contents

mysql_affected_rows -- Get number of affected rows in previous MySQL operation

mysql_change_user -- Change logged in user of the active connection

mysql_client_encoding -- Returns the name of the character set

mysql_close -- Close MySQL connection

mysql_connect -- Open a connection to a MySQL Server

mysql_create_db -- Create a MySQL database

mysql_data_seek -- Move internal result pointer

mysql_db_name -- Get result data

mysql_db_query -- Send a MySQL query

mysql_drop_db -- Drop (delete) a MySQL database


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysql_errno -- Returns the numerical value of the error message from previous MySQL operation

mysql_error -- Returns the text of the error message from previous MySQL operation

mysql_escape_string -- Escapes a string for use in a mysql_query

mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

mysql_fetch_assoc -- Fetch a result row as an associative array

mysql_fetch_field -- Get column information from a result and return as an object

mysql_fetch_lengths -- Get the length of each output in a result

mysql_fetch_object -- Fetch a result row as an object

mysql_fetch_row -- Get a result row as an enumerated array

mysql_field_flags -- Get the flags associated with the specified field in a result

mysql_field_len -- Returns the length of the specified field

mysql_field_name -- Get the name of the specified field in a result

mysql_field_seek -- Set result pointer to a specified field offset

mysql_field_table -- Get name of the table the specified field is in

mysql_field_type -- Get the type of the specified field in a result

mysql_free_result -- Free result memory

mysql_get_client_info -- Get MySQL client info

mysql_get_host_info -- Get MySQL host info

mysql_get_proto_info -- Get MySQL protocol info

mysql_get_server_info -- Get MySQL server info

mysql_info -- Get information about the most recent query

mysql_insert_id -- Get the ID generated from the previous INSERT operation

mysql_list_dbs -- List databases available on a MySQL server

mysql_list_fields -- List MySQL table fields

mysql_list_processes -- List MySQL processes

mysql_list_tables -- List tables in a MySQL database

mysql_num_fields -- Get number of fields in result

mysql_num_rows -- Get number of rows in result


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysql_pconnect -- Open a persistent connection to a MySQL server

mysql_ping -- Ping a server connection or reconnect if there is no connection

mysql_query -- Send a MySQL query

mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement

mysql_result -- Get result data

mysql_select_db -- Select a MySQL database

mysql_stat -- Get current system status

mysql_tablename -- Get table name of field

mysql_thread_id -- Return the current thread ID

mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the
result rows

Improved MySQL Extension

The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above.
More information about the MySQL Database server can be found at http://www.mysql.com/

Documentation for MySQL can be found at http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of MySQL AB.

Table of Contents

mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation

mysqli_autocommit -- Turns on or off auto-commiting database modifications

mysqli_bind_param -- Alias for mysqli_stmt_bind_param()

mysqli_bind_result -- Alias for mysqli_stmt_bind_result()

mysqli_change_user -- Changes the user of the specified database connection

mysqli_character_set_name -- Returns the default character set for the database connection

mysqli_client_encoding -- Alias of mysqli_character_set_name()

mysqli_close -- Closes a previously opened database connection

mysqli_commit -- Commits the current transaction


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysqli_connect_errno -- Returns the error code from last connect call

mysqli_connect_error -- Returns a string description of the last connect error

mysqli_connect -- Open a new connection to the MySQL server

mysqli_data_seek -- Adjusts the result pointer to an arbitary row in the result

mysqli_debug -- Performs debugging operations

mysqli_disable_reads_from_master -- Disable reads from master

mysqli_disable_rpl_parse -- Disable RPL parse

mysqli_dump_debug_info -- Dump debugging information into the log

mysqli_embedded_connect -- Open a connection to an embedded mysql server

mysqli_enable_reads_from_master -- Enable reads from master

mysqli_enable_rpl_parse -- Enable RPL parse

mysqli_errno -- Returns the error code for the most recent function call

mysqli_error -- Returns a string description of the last error

mysqli_escape_string -- Alias of mysqli_real_escape_string()

mysqli_execute -- Alias for mysqli_stmt_execute()

mysqli_fetch_array -- Fetch a result row as an associative, a numeric array, or both

mysqli_fetch_assoc -- Fetch a result row as an associative array

mysqli_fetch_field_direct -- Fetch meta-data for a single field

mysqli_fetch_field -- Returns the next field in the result set

mysqli_fetch_fields -- Returns an array of objects representing the fields in a result set

mysqli_fetch_lengths -- Returns the lengths of the columns of the current row in the result set

mysqli_fetch_object -- Returns the current row of a result set as an object

mysqli_fetch_row -- Get a result row as an enumerated array

mysqli_fetch -- Alias for mysqli_stmt_fetch()

mysqli_field_count -- Returns the number of columns for the most recent query

mysqli_field_seek -- Set result pointer to a specified field offset

mysqli_field_tell -- Get current field offset of a result pointer

mysqli_free_result -- Frees the memory associated with a result


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysqli_get_client_info -- Returns the MySQL client version as a string

mysqli_get_client_version -- Get MySQL client info

mysqli_get_host_info -- Returns a string representing the type of connection used

mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()

mysqli_get_proto_info -- Returns the version of the MySQL protocol used

mysqli_get_server_info -- Returns the version of the MySQL server

mysqli_get_server_version -- Returns the version of the MySQL server as an integer

mysqli_info -- Retrieves information about the most recently executed query

mysqli_init -- Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli_insert_id -- Returns the auto generated id used in the last query

mysqli_kill -- Asks the server to kill a MySQL thread

mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup

mysqli_more_results -- Check if there any more query results from a multi query

mysqli_multi_query -- Performs a query on the database

mysqli_next_result -- Prepare next result from multi_query

mysqli_num_fields -- Get the number of fields in a result

mysqli_num_rows -- Gets the number of rows in a result

mysqli_options -- Set options

mysqli_param_count -- Alias for mysqli_stmt_param_count()

mysqli_ping -- Pings a server connection, or tries to reconnect if the connection has gone down

mysqli_prepare -- Prepare a SQL statement for execution

mysqli_query -- Performs a query on the database

mysqli_real_connect -- Opens a connection to a mysql server

mysqli_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking
into account the current charset of the connection

mysqli_real_query -- Execute an SQL query

mysqli_report -- Enables or disables internal report functions

mysqli_rollback -- Rolls back current transaction


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysqli_rpl_parse_enabled -- Check if RPL parse is enabled

mysqli_rpl_probe -- RPL probe

mysqli_rpl_query_type -- Returns RPL query type

mysqli_select_db -- Selects the default database for database queries

mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()

mysqli_send_query -- Send the query and return

mysqli_server_end -- Shut down the embedded server

mysqli_server_init -- Initialize embedded server

mysqli_set_charset -- Sets the default client character set

mysqli_set_opt -- Alias of mysqli_options()

mysqli_sqlstate -- Returns the SQLSTATE error from previous MySQL operation

mysqli_ssl_set -- Used for establishing secure connections using SSL

mysqli_stat -- Gets the current system status

mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the
last executed statement

mysqli_stmt_bind_param -- Binds variables to a prepared statement as parameters

mysqli_stmt_bind_result -- Binds variables to a prepared statement for result storage

mysqli_stmt_close -- Closes a prepared statement

mysqli_stmt_data_seek -- Seeks to an arbitray row in statement result set

mysqli_stmt_errno -- Returns the error code for the most recent statement call

mysqli_stmt_error -- Returns a string description for last statement error

mysqli_stmt_execute -- Executes a prepared Query

mysqli_stmt_fetch -- Fetch results from a prepared statement into the bound variables

mysqli_stmt_free_result -- Frees stored result memory for the given statement handle

mysqli_stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli_stmt_num_rows -- Return the number of rows in statements result set

mysqli_stmt_param_count -- Returns the number of parameter for the given statement

mysqli_stmt_prepare -- Prepare a SQL statement for execution


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

mysqli_stmt_reset -- Resets a prepared statement

mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement

mysqli_stmt_send_long_data -- Send data in blocks

mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation

mysqli_stmt_store_result -- Transfers a result set from a prepared statement

mysqli_store_result -- Transfers a result set from the last query

mysqli_thread_id -- Returns the thread ID for the current connection

mysqli_thread_safe -- Returns whether thread safety is given or not

mysqli_use_result -- Initiate a result set retrieval

mysqli_warning_count -- Returns the number of warnings from the last query for the given link

Connecting PHP to a MySQL database:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Close the connection:


In MySQLi Procedural language, it can be written as:

mysqli_close($conn);

Create Database Using PHP

A database consists of one or more tables.


Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

You will need special CREATE privileges to create or to delete a MySQL


database.

Create a MySQL Database Using MySQLi

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Create Table Using PHP

We can create table using PHP after establishing connection with a mySQL
database.
<?php
// Create connection
$link = mysqli_connect("localhost", "root", "", "student");
Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$sql="CREATE TABLE `student`.`course`


(`cid` INT( 8 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`course-code` VARCHAR( 10 ) NOT NULL ,
`course-title` VARCHAR( 255 ) NOT NULL)
";

/* Create table doesn't return a resultset */


if (mysqli_query($link, $sql) === TRUE) {
printf("Table course successfully created.\n");
}
mysqli_close($link);
?>

Inserting Data into a Database Table

We can insert data to a database named “mydb” by the following PHP code.

Example-1
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

Example-2
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

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


VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Insert Multiple Data


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

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


VALUES ('John', 'Doe', '[email protected]');";
Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

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


VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";

if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Insert Form Data

Consider a form with three fields. Then we can input data into myguests table of a
MySQL database using following program.

<?php

echo $_POST["submit"];

If($_REQUEST["submit"]=="Submit")

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "student";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

$firstname = $_REQUEST["fname"];
Managing Data with PHP and MySQL
Prepared By Dr. Tushar Kanti Saha, Assoc. Prof. CSE, JKKNIU.

$lastname =$_REQUEST["lname"];

$email = $_REQUEST["email"];;

echo $sql = "INSERT INTO guest(gid, firstname, lastname, email)

VALUES ('NULL','$firstname', '$lastname', '$email')";

if (mysqli_query($conn, $sql)) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

mysqli_close($conn);

?>

<html>

<head>

<title>Page title</title>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

<label for="fname">First name:</label><br>

<input type="text" id="fname" name="fname"><br>

<label for="lname">Last name:</label><br>

<input type="text" id="lname" name="lname"><br>

<label for="email">Email:</label><br>

<input type="text" id="email" name="email"><br>

<input type="submit" id="submit" name="submit" value="Submit">

</form>

</html>

You might also like