0% found this document useful (0 votes)
5 views25 pages

PHP Notes2

The document discusses various PHP functions for connecting to a MySQL database and performing CRUD operations. It explains functions like mysql_connect, mysql_query, mysql_select_db for connecting to databases and performing queries. It also discusses similar functions in MySQLi like mysqli_connect, mysqli_query for object-oriented connections and queries.

Uploaded by

abinrj123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views25 pages

PHP Notes2

The document discusses various PHP functions for connecting to a MySQL database and performing CRUD operations. It explains functions like mysql_connect, mysql_query, mysql_select_db for connecting to databases and performing queries. It also discusses similar functions in MySQLi like mysqli_connect, mysqli_query for object-oriented connections and queries.

Uploaded by

abinrj123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

• PHP provides mysql_connect function to open a

database connection. This function takes five parameters


and returns a MySQL link identifier on success, or FALSE
on failure.
• connection
mysql_connect(server,user,passwd,new_link,client_flag);
Parameter & Description

server
Optional − The host name running database server. If not specified then default value is localhost:3306.
user
Optional − The username accessing the database. If not specified then default is the name of the user that owns the server process.

passwd
Optional − The password of the user accessing the database. If not specified then default is an empty password.

new_link
Optional − If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the
identifier of the already opened connection will be returned.

client_flags
Optional − A combination of the following constants −
•MYSQL_CLIENT_SSL − Use SSL encryption
•MYSQL_CLIENT_COMPRESS − Use compression protocol
•MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
•MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser,
$dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• mysql_close($conn);
• ?>
• Using MySQLi object-oriented procedure: We can use the
MySQLi object-oriented procedure to establish a connection
to MySQL database from a PHP script.
• Syntax:
• <?php
• $servername = "localhost";
• $username = "username";
• $password = "password";
• // Creating connection
• $conn = new mysqli($servername, $username, $password);
• // Checking connection
• if ($conn->connect_error) {
• die("Connection failed: " . $conn->connect_error);
•}
• echo "Connected successfully";
• $conn->close();
• ?>
• PHP uses mysql_query function to create a MySQL
database. This function takes two parameters and
returns TRUE on success or FALSE on failure.
• bool mysql_query( sql, connection );

Sr.No Parameter & Description


1 sql
Required - SQL query to create a database
2 connection
Optional - if not specified then last opend connection by
mysql_connect will be used.
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• $sql = 'CREATE Database test_db';
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not create database: ' . mysql_error());
• }
• echo "Database test_db created successfully\n";
• mysql_close($conn);
• ?>
• // Creating a database named newDB
• $sql = "CREATE DATABASE newDB";
• if ($conn->query($sql) === TRUE) {
• echo "Database created successfully with the
name newDB";
• } else {
• echo "Error creating database: " . $conn->error;
•}
• PHP provides function mysql_select_db to select a
database. It returns TRUE on success or FALSE on failure.
• bool mysql_select_db( db_name, connection );

Sr.No Parameter & Description


1 db_name
Required - Database name to be selected
2 connection
Optional - if not specified then last opend connection by
mysql_connect will be used.
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• mysql_select_db( 'test_db' );
• mysql_close($conn);

• ?>
• <?php
• $dbhost = 'localhost:3036'; $dbuser = 'root';$dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• $sql = 'CREATE TABLE employee( '.
• 'emp_id INT NOT NULL AUTO_INCREMENT, '.
• 'emp_name VARCHAR(20) NOT NULL, '.
• 'emp_address VARCHAR(20) NOT NULL, '.
• 'emp_salary INT NOT NULL, '.
• 'join_date timestamp(14) NOT NULL, '.
• 'primary key ( emp_id ))';
• mysql_select_db('test_db');
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not create table: ' . mysql_error());
• }
• echo "Table employee created successfully\n";
• mysql_close($conn);
• ?>
• // sql code to create table
• $sql = "CREATE TABLE employees(
• id INT(2) PRIMARY KEY,
• firstname VARCHAR(30) NOT NULL,
• lastname VARCHAR(30) NOT NULL,
• email VARCHAR(50)
• )";
• if ($conn->query($sql) === TRUE) {
• echo "Table employees created successfully";
• } else {
• echo "Error creating table: " . $conn->error;
•}
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• $sql = 'INSERT INTO employee '.
• '(emp_name,emp_address, emp_salary, join_date) '.
• 'VALUES ( "guest", "XYZ", 2000, NOW() )';
• mysql_select_db('test_db');
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not enter data: ' . mysql_error());
• }
• echo "Entered data successfully\n";
• mysql_close($conn);
• ?>
• <?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 = "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();
• ?>
• $emp_name = $_POST['emp_name'];
• $emp_address = $_POST['emp_address'];
• $emp_salary = $_POST['emp_salary'];
• $sql = "INSERT INTO employee (emp_name,emp_address, emp_salary,
• join_date) VALUES('$emp_name','$emp_address',$emp_salary, NOW())";
• mysql_select_db('test_db');
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not enter data: ' . mysql_error());
• }

• <?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 = "UPDATE MyGuests SET lastname='Doe' WHERE
id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
• <?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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
• $emp_id = $_POST['emp_id'];
• $sql = "DELETE FROM employee WHERE emp_id =
$emp_id" ;
• mysql_select_db('test_db');
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not delete data: ' . mysql_error());
• }
• echo "Deleted data successfully\n";
• mysql_close($conn);
PHP mysql_fetch_row() Function
• mysql_fetch_row() fetches one row of data from the
result associated with the specified result identifier. The
row is returned as an array. Each result column is stored
in an array offset, starting at offset 0.
• <?php
$result = mysql_query("SELECT id,email FROM people W
HERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
• <?php
$con =
mysqli_connect("localhost","my_user","my_password","my_d
b");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql = "SELECT Lastname, Age FROM Persons ORDER BY
Lastname";
if ($result = mysqli_query($con, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
echo “Last name: “+$row[0]+”Age: ”+ $row[1];
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
• <?php
• $sql = "SELECT Lastname, Age FROM Persons
ORDER BY Lastname";
• if ($result = $mysqli -> query($sql)) {
• while ($row = $result -> fetch_row()) {
• echo “Last name: “+$row[0]+”Age: ”+ $row[1];
• }
• $result -> free_result();
•}
• $mysqli -> close();
• ?>
• Mysqli_fetch_assoc()
• Fetch a result row as an associative array.This
function will return a row as an associative array
where the column names will be the keys storing
corresponding value.
• PHP mysql_fetch_array() Function
• Fetch a result row as an associative array, a numeric
array and also it fetches by both associative &
numeric array.
• <?php
• $con = mysqli_connect("localhost","root","","test");
• // Check connection
• if (mysqli_connect_errno())
• {
• echo "Failed to connect to MySQL: " . mysqli_connect_error();
• }
• $result = mysqli_query($con,"select * from user");
• while ($rows = mysqli_fetch_assoc($result))
• {
• echo $rows['id'];echo "<br>";
• echo $rows['name']; echo "<br>";
• echo $rows['email']; echo "<br>";
• echo $rows['contactno']; echo "<br>";
• echo $rows['addrss']; echo "<br>";
• echo $rows['posting_date']; echo "<br>";
• }
• ?>
• <?php
• $con = mysqli_connect("localhost","root","","test");
• // Check connection
• if (mysqli_connect_errno())
• {
• echo "Failed to connect to MySQL: " . mysqli_connect_error();
• }
• $result = mysqli_query($con,"select * from user");
• while ($rows = mysqli_fetch_arrayc($result))
• {
• echo $rows['id']; echo "<br>";
• echo $rows['name']; echo "<br>";
• echo $rows['email']; echo "<br>";
• echo $rows['contactno']; echo "<br>";
• echo $rows['addrss']; echo "<br>";
• echo $rows['posting_date']; echo "<br>";
• /* Now here both associative array and numeric array will work. */
• echo $rows[0]; echo "<br>"; echo $rows[1]; echo "<br>";
• echo $rows[2]; echo "<br>"; echo $rows[3]; echo "<br>";
• echo $rows[4]; echo "<br>"; echo $rows[5]; echo "<br>";
• }
• ?>
mysql_result()
• mysql_result ( resource $result , int $row [, mixed $field = 0 ] )
• Retrieves the contents of one cell from a MySQL result set.
• <?php
• $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
• if (!$link) {
• die('Could not connect: ' . mysql_error());
• }
• if (!mysql_select_db('database_name')) {
• die('Could not select database: ' . mysql_error());
• }
• $result = mysql_query('SELECT name FROM work.employee');
• if (!$result) {
• die('Could not query:' . mysql_error());
• }
• echo mysql_result($result, 2); // outputs third employee's name
• mysql_close($link);
• ?>
• mysql_list_fields():- call this function to get
information on table fields. It makes three
arguments ( a database name, a table name, and
an optional link identifier) and returns a result
pointer that refers to a list of all the fields in the
specified database.
• mysql_num_fields():- this takes a result pointer (as
returned by the preceding function) and returns
the total number of fields from the result set to
which it points.
• <?php
$result = mysql_query("SELECT id,email FROM peo
ple WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

/* returns 2 because id,email === two fields */


echo mysql_num_fields($result);
?>

You might also like