unit5 web.
unit5 web.
mysqli_connect()
• mysqli_connect() gives access to any databases that are assigned to the user.
• The mysqli_connect() function opens a new connection to the MySQL server.
• If you give an invalid login set, it would generate an error, and the exception
handling would allow the application to die gracefully.
Syntax
mysqli_connect(host,username,password,dbname,port,socket);
Parameter Description
port Optional. Specifies the port number to attempt to connect to the MySQL server
Example
<?php
$host = "localhost";
$username = "";
$password = "";
$dbname = "sform";
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connection Succees....";
mysqli_close($conn);
?>
Mysqli_close()
Syntax
mysqli_close(connection);
Parameter Description
Example
<?php
$conn = mysqli_connect($host, $username, $password, $dbname);
mysqli_close($con);
?>
QUERYING THE DATABASE
Syntax
mysqli_query(connection,query,resultmode);
Parameter Description
Example
<?php
$conn = mysqli_connect($host, $username, $password, $dbname);
// Perform queries
mysqli_query($con,"SELECT * FROM sform");
mysqli_query($con,"INSERT INTO sform (name,fname,mname,dob,mno)
VALUES ('rishi','ritvik',’s’,12-oct-2006)");
mysqli_close($con);
?>
(ii) PHP mysqli_select_db() Function
The mysqli_select_db() function is used to change the default database for the
connection.
Syntax
mysqli_select_db(connection,dbname);
Parameter Description
Example
<?php
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
mysqli_close($conn);
?>
RETRIEVING AND DISPLAYING RESULTS
In PHP, the most common method to retrieve a row in the database is with the
mysql_fetch_array() function.
Parameter Description
resulttype Optional. Specifies what type of array that should be produced. Can be
one of the following values:
• MYSQLI_ASSOC
• MYSQLI_NUM
• MYSQLI_BOTH
<?php
$conn = mysqli_connect($host, $username, $password, $dbname);
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
Example :
Table name : "MyGuests"
id firstname lastname email
The following examples update the record with id=1 in the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->close();
?>
After the record is deleted, the table will look like this: