You are on page 1of 18

MYSQL AND PHP DATABASE CONNECTIVITY How to Show Data of sql in tabular form

<!DOCTYPE html>
<html>
How to show data from sql tables? <head>
<!DOCTYPE html> <style>
<html> table, th, td {
<body> border: 1px solid black;
<?php }
$servername = "localhost"; </style>
$username = "username"; </head>
$password = "password"; <body>
$dbname = "myDB"; <?php
// Create connection $servername = "localhost";
$conn = new mysqli($servername, $username, $password, $dbname); $username = "username";
// Check connection $password = "password";
if ($conn->connect_error) { $dbname = "myDB";
die("Connection failed: " . $conn->connect_error); // Create connection
} $conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, firstname, lastname FROM MyGuests"; // Check connection
$result = $conn->query($sql); if ($conn->connect_error) {
if ($result->num_rows > 0) { die("Connection failed: " . $conn->connect_error);
// output data of each row }
while($row = $result->fetch_assoc()) { $sql = "SELECT id, firstname, lastname FROM MyGuests";
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $result = $conn->query($sql);
$row["lastname"] . "<br>"; if ($result->num_rows > 0) {
} echo "<table><tr><th>ID</th><th>Name</th></tr>";
} else { // output data of each row
echo "0 results"; while($row = $result->fetch_assoc()) {
} echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " .
$conn->close(); $row["lastname"]. "</td></tr>";
?> }
</body> echo "</table>";
</html> } else {
echo "0 results";
}
$conn->close(); ?> </body> </html>

1
Program to use SQL Procedure to show database data Using PDO Technique for database connectivity
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<?php <?php
$servername = "localhost"; echo "<table style='border: solid 1px black;'>";
$username = "username"; echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
$password = "password"; class TableRows extends RecursiveIteratorIterator {
$dbname = "myDB"; function __construct($it) {
// Create connection parent::__construct($it, self::LEAVES_ONLY);
$conn = mysqli_connect($servername, $username, $password, }
$dbname); function current() {
// Check connection return "<td style='width: 150px; border: 1px solid black;'>" .
if (!$conn) { parent::current(). "</td>";
die("Connection failed: " . mysqli_connect_error()); }
} function beginChildren() {
$sql = "SELECT id, firstname, lastname FROM MyGuests"; echo "<tr>";
$result = mysqli_query($conn, $sql); }
function endChildren() {
if (mysqli_num_rows($result) > 0) { echo "</tr>" . "\n";
// output data of each row }
while($row = mysqli_fetch_assoc($result)) { }
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $servername = "localhost";
$row["lastname"]. "<br>"; $username = "username";
} $password = "password";
} else { $dbname = "myDBPDO";
echo "0 results"; try {
} $conn = new PDO("mysql:host=$servername;dbname=$dbname",
mysqli_close($conn); $username, $password);
?> $conn->setAttribute(PDO::ATTR_ERRMODE,
</body> PDO::ERRMODE_EXCEPTION);
</html> $stmt = $conn->prepare("SELECT id, firstname, lastname FROM
MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

2
foreach(new TableRows(new RecursiveArrayIterator($stmt- Definition and Usage
>fetchAll())) as$k=>$v) {
echo $v; The mysqli_affected_rows() function returns the number of affected
} rows in the previous SELECT, INSERT, UPDATE, REPLACE, or
} DELETE query.
catch(PDOException $e) {
Syntax
echo "Error: " . $e->getMessage();
mysqli_affected_rows(connection);
}
$conn = null;
echo "</table>";
?> Parameter Description
</body>
</html>
Mysql Affected Rows function Details connection Required. Specifies the MySQL connection to
Example use

Print out affected rows from different queries: mysqli_autocommit() Function


<?php Example
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) Turn off auto-committing, make some queries, then commit the queries:
{ <?php
echo "Failed to connect to MySQL: " . mysqli_connect_error(); $con=mysqli_connect("localhost","my_user","my_password","my_db");
} // Check connection
if (mysqli_connect_errno())
// Perform queries and print out affected rows {
mysqli_query($con,"SELECT * FROM Persons"); echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Affected rows: " . mysqli_affected_rows($con); }

mysqli_query($con,"DELETE FROM Persons WHERE Age>32"); // Set autocommit to off


echo "Affected rows: " . mysqli_affected_rows($con); mysqli_autocommit($con,FALSE);

mysqli_close($con); // Insert some values


?> mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Peter','Griffin',35)");
mysqli_query($con,"INSERT INTO Persons
(FirstName,LastName,Age)
3
VALUES ('Glenn','Quagmire',33)"); <?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Commit transaction
mysqli_commit($con); // Check connection
if (mysqli_connect_errno())
// Close connection {
mysqli_close($con); echo "Failed to connect to MySQL: " . mysqli_connect_error();
?> }
Definition and Usage
// Reset all and select a new database
mysqli_change_user($con, "my_user", "my_password", "my_test");
The mysqli_autocommit() function turns on or off auto-committing
database modifications.
mysqli_close($con);
?>
Tip: Also look at the mysqli_commit() function, which commits the
current transaction for the specified database connection, and Definition and Usage
the mysqli_rollback() function, which rolls back the current transaction.
The mysqli_change_user() function changes the user of the specified
Syntax
database connection, and sets the current database.
mysqli_autocommit(connection,mode);
Syntax
mysqli_change_user(connection,username,password,dbname);
Parameter Description

connection Required. Specifies the MySQL Parameter Description


connection to use
connection Required. Specifies the MySQL connection to
mode Required. FALSE turns auto-commit off. use
TRUE turns auto-commit on (and
commits any waiting queries) username Required. Specifies the MySQL username

password Required. Specifies the MySQL password


mysqli_change_user() Function
dbname Required. Specifies the database to change to
Example

Change the user of the specified database connection:

4
mysqli_close() Function if (mysqli_connect_errno())
{
Example
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Close a previously opened database connection:
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db"); Definition and Usage

// ....some PHP code... The mysqli_connect() function opens a new connection to the MySQL
server.
mysqli_close($con);
Syntax
?>
mysqli_connect(host,username,password,dbname,port,socket);
Definition and Usage
Parameter Description
The mysqli_close() function closes a previously opened database
connection. host Optional. Specifies a host name or an IP
Syntax address
mysqli_close(connection);
username Optional. Specifies the MySQL username

Parameter Description password Optional. Specifies the MySQL password

connection Required. Specifies the MySQL dbname Optional. Specifies the default database to
connection to close be used

port Optional. Specifies the port number to


mysqli_connect() Function attempt to connect to the MySQL server

Example socket Optional. Specifies the socket or named pipe


to be used
Open a new connection to the MySQL server:
<?php
$con = mysqli_data_seek() Function
mysqli_connect("localhost","my_user","my_password","my_db");
Example
// Check connection
Seek to row number 15 in the result-set:
5
<?php result Required. Specifies a result set
$con=mysqli_connect("localhost","my_user","my_password","my_db");
identifier returned by mysqli_query(),
// Check connection
mysqli_store_result() or
if (mysqli_connect_errno())
mysqli_use_result()
{
echo "Failed to connect to MySQL: " . mysqli_connect_error(); offset Required. Specifies the field offset.
} Must be between 0 and the total
number of rows - 1
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
mysqli_fetch_all() Function
if ($result=mysqli_query($con,$sql))
{ Example
// Seek to row number 15
mysqli_data_seek($result,14); Fetch all rows and return the result-set as an associative array:
<?php
// Fetch row $con=mysqli_connect("localhost","my_user","my_password","my_db");
$row=mysqli_fetch_row($result); // Check connection
if (mysqli_connect_errno())
printf ("Lastname: %s Age: %s\n", $row[0], $row[1]); {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// Free result set }
mysqli_free_result($result);
} $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
mysqli_close($con);
?> // Fetch all
mysqli_fetch_all($result,MYSQLI_ASSOC);
Definition and Usage
// Free result set
The mysqli_data_seek() function adjusts the result pointer to an arbitrary mysqli_free_result($result);
row in the result-set.
Syntax mysqli_close($con);
mysqli_data_seek(result,offset); ?>
Definition and Usage
Parameter Description

6
The mysqli_fetch_all() function fetches all result rows and returns the {
result-set as an associative array, a numeric array, or both. echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Note: This function is available only with MySQL Native Driver.
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
Syntax
$result=mysqli_query($con,$sql);
mysqli_fetch_all(result,resulttype);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
Parameter Description printf ("%s (%s)\n",$row[0],$row[1]);

// Associative array
result Required. Specifies a result set identifier $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
returned by mysqli_query(), printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
mysqli_store_result() or
mysqli_use_result() // Free result set
mysqli_free_result($result);

resulttype Optional. Specifies what type of array mysqli_close($con);


that should be produced. Can be one of ?>
the following values:
Definition and Usage
MYSQLI_ASSOC
MYSQLI_NUM The mysqli_fetch_array() function fetches a result row as an associative
MYSQLI_BOTH array, a numeric array, or both.

Note: Fieldnames returned from this function are case-sensitive.


mysqli_fetch_array() Function Syntax
mysqli_fetch_array(result,resulttype);
Example

Fetch a result row as a numeric array and as an associative array:


<?php Parameter Description
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) result Required. Specifies a result set identifier

7
returned by mysqli_query(),
mysqli_close($con);
mysqli_store_result() or
?>
mysqli_use_result()
Definition and Usage

resulttype Optional. Specifies what type of array that The mysqli_fetch_assoc() function fetches a result row as an associative
should be produced. Can be one of the array.
following values:
Note: Fieldnames returned from this function are case-sensitive.
MYSQLI_ASSOC
MYSQLI_NUM Syntax
MYSQLI_BOTH mysqli_fetch_assoc(result);

mysqli_fetch_assoc() Function Parameter Description


Example
result Required. Specifies a result set identifier
Fetch a result row as an associative array: returned by mysqli_query(),
<?php mysqli_store_result() or mysqli_use_result()
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{ mysqli_fetch_field_direct() Function
echo "Failed to connect to MySQL: " . mysqli_connect_error(); Example
}
Return meta-data for a single field (column) in the result set, then print
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; the field's name, table, and max length:
$result=mysqli_query($con,$sql); <?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Associative array // Check connection
$row=mysqli_fetch_assoc($result); if (mysqli_connect_errno())
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]); {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// Free result set }
mysqli_free_result($result);

8
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
be an integer between 0 and number of fields
-1
if ($result=mysqli_query($con,$sql))
{
mysqli_fetch_field() Function
// Get field information for "Age"
$fieldinfo=mysqli_fetch_field_direct($result,1); Example

printf("Name: %s\n",$fieldinfo->name); Return the next field (column) in the result set, then print each field's
printf("Table: %s\n",$fieldinfo->table); name, table, and max length:
printf("max. Len: %d\n",$fieldinfo->max_length); <?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Free result set // Check connection
mysqli_free_result($result); if (mysqli_connect_errno())
} {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con); }
?>
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
Definition and Usage
if ($result=mysqli_query($con,$sql))
The mysqli_fetch_field_direct() function returns meta-data for a single
{
field (column) in the result set, as an object.
// Get field information for all fields
Syntax while ($fieldinfo=mysqli_fetch_field($result))
mysqli_fetch_field_direct(result,fieldnr); {
printf("Name: %s\n",$fieldinfo->name);
printf("Table: %s\n",$fieldinfo->table);
printf("max. Len: %d\n",$fieldinfo->max_length);
Parameter Description }
// Free result set
mysqli_free_result($result);
result Required. Specifies a result set identifier
}
returned by mysqli_query(),
mysqli_store_result() or mysqli_use_result()
mysqli_close($con);
?>
fieldnr Required. Specifies the field number. Must Definition and Usage

9
The mysqli_fetch_field() function returns the next field (column) in the
result set, as an object. foreach ($fieldinfo as $val)
{
Syntax
printf("Name: %s\n",$val->name);
mysqli_fetch_field(result);
printf("Table: %s\n",$val->table);
printf("max. Len: %d\n",$val->max_length);
}
Parameter Description // Free result set
mysqli_free_result($result);
}
result Required. Specifies a result set identifier
returned by mysqli_query(), mysqli_close($con);
mysqli_store_result() or ?>
mysqli_use_result()
Definition and Usage
mysqli_fetch_fields() Function
The mysqli_fetch_fields() function returns an array of objects that
represent the fields (columns) in a result set.

Example Syntax
mysqli_fetch_fields(result);
Return an array of objects that represent the fields (columns) in a result
set, then print each field's name, table, and max length:
<?php Parameter Description
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) result Required. Specifies a result set identifier
{ returned by mysqli_query(),
echo "Failed to connect to MySQL: " . mysqli_connect_error(); mysqli_store_result() or mysqli_use_result()
}
mysqli_fetch_row() Function
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
Example
if ($result=mysqli_query($con,$sql))
Fetch rows from a result-set:
{
<?php
// Get field information for all fields
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$fieldinfo=mysqli_fetch_fields($result);
10
// Check connection
mysqli_query(),
if (mysqli_connect_errno())
mysqli_store_result() or
{
mysqli_use_result()
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_field_count() Function
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; Example

if ($result=mysqli_query($con,$sql)) Assume we have a "Friends" table that has 3 fields and 20 rows. Return
{ the number of columns for the most recent query:
// Fetch one and one row <?php
while ($row=mysqli_fetch_row($result)) $con=mysqli_connect("localhost","my_user","my_password","my_db");
{ // Check connection
printf ("%s (%s)\n",$row[0],$row[1]); if (mysqli_connect_errno())
} {
// Free result set echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_free_result($result); }
}
mysqli_query($con,"SELECT * FROM Friends");
mysqli_close($con); // Get number of columns - will always return 3
?> mysqli_field_count($con);
Definition and Usage
mysqli_close($con);
?>
The mysqli_fetch_row() function fetches one row from a result-set and
returns it as an enumerated array. Definition and Usage
Syntax
The mysqli_field_count() function returns the number of columns for the
mysqli_fetch_row(result);
most recent query.

Parameter Description
Syntax
mysqli_field_count(connection);
result Required. Specifies a result set mysqli_field_seek() Function
identifier returned by
Example

11
Set the field cursor to the first field (column) in the result set, then get
the field info with mysqli_fetch_field() and print the field's name, table,
and max length:
Parameter Description
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection result Required. Specifies a result set identifier
if (mysqli_connect_errno()) returned by mysqli_query(),
{ mysqli_store_result() or
echo "Failed to connect to MySQL: " . mysqli_connect_error(); mysqli_use_result()
}

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; fieldnr Required. Specifies the field number.
Must be an integer between 0 and number
if ($result=mysqli_query($con,$sql)) of fields -1
{
// Get field info for 1st column ("Lastname") Example
mysqli_field_seek($result,0);
$fieldinfo=mysqli_fetch_field($result); Fetch rows from a result-set, then free the memory associated with the
result:
printf("Name: %s\n",$fieldinfo->name); <?php
printf("Table: %s\n",$fieldinfo->table); $con=mysqli_connect("localhost","my_user","my_password","my_db");
printf("max. Len: %d\n",$fieldinfo->max_length); // Check connection
if (mysqli_connect_errno())
// Free result set {
mysqli_free_result($result); echo "Failed to connect to MySQL: " . mysqli_connect_error();
} }

mysqli_close($con); $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";


?>
Definition and Usage if ($result=mysqli_query($con,$sql))
{
The mysqli_field_seek() function sets the field cursor to the given field // Fetch one and one row
offset. while ($row=mysqli_fetch_row($result))
{
Syntax printf ("%s (%s)\n",$row[0],$row[1]);
mysqli_field_seek(result,fieldnr); }
12
// Free result set
mysqli_free_result($result); $sql = "SELECT Lastname FROM Persons ORDER BY LastName;";
} $sql .= "SELECT Country FROM Customers";

mysqli_close($con); // Execute multi query


?> if (mysqli_multi_query($con,$sql))
{
Definition and Usage
do
{
The mysqli_free_result() function frees the memory associated with the
// Store first result set
result.
if ($result=mysqli_store_result($con)) {
Syntax // Fetch one and one row
mysqli_free_result(result); while ($row=mysqli_fetch_row($result))
{
printf("%s\n",$row[0]);
}
Parameter Description
// Free result set
mysqli_free_result($result);
result Required. Specifies a result set identifier }
returned by mysqli_query(), }
mysqli_store_result() or mysqli_use_result() while (mysqli_next_result($con));
}
mysqli_multi_query() Function
mysqli_close($con);
?>

Example Definition and Usage

Perform multiple queries against the database: The mysqli_multi_query() function performs one or more queries against
<?php the database. The queries are separated with a semicolon.
$con=mysqli_connect("localhost","my_user","my_password","my_db"); Syntax
// Check connection mysqli_multi_query(connection,query);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} Parameter Description

13
}
mysqli_free_result($con);
connection Required. Specifies the MySQL
}
connection to use
}
while (mysqli_next_result($con));
query Required. Specifies one or more }
queries, seperated with semicolon
mysqli_close($con);
mysqli_next_result() Function ?>

Example Definition and Usage

Perform multiple queries against the database. Use mysqli_next_result() The mysqli_next_result() function prepares the next result set
function to prepare the next result set: from mysqli_multi_query().
<?php Syntax
$con=mysqli_connect("localhost","my_user","my_password","my_db"); mysqli_next_result(connection);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error(); Parameter Description
}
connection Required. Specifies the MySQL
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;";
connection to use
$sql .= "SELECT Country FROM Customers";
mysqli_num_fields() Function
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do Example
{
// Store first result set Return the number of fields (columns) in a result set:
if ($result=mysqli_store_result($con)) <?php
{ $con=mysqli_connect("localhost","my_user","my_password","my_db");
while ($row=mysqli_fetch_row($result)) // Check connection
{ if (mysqli_connect_errno())
printf("%s\n",$row[0]); {

14
echo "Failed to connect to MySQL: " . mysqli_connect_error(); Example
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; Return the number of rows in a result set:
<?php
if ($result=mysqli_query($con,$sql)) $con=mysqli_connect("localhost","my_user","my_password","my_db");
{ // Check connection
// Return the number of fields in result set if (mysqli_connect_errno())
$fieldcount=mysqli_num_fields($result); {
printf("Result set has %d fields.\n",$fieldcount); echo "Failed to connect to MySQL: " . mysqli_connect_error();
// Free result set }
mysqli_free_result($result);
} $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

mysqli_close($con); if ($result=mysqli_query($con,$sql))
?> {
// Return the number of rows in result set
Definition and Usage
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
The mysqli_num_fields() function returns the number of fields
// Free result set
(columns) in a result set.
mysqli_free_result($result);
Syntax }
mysqli_num_fields(result);
mysqli_close($con);
?>
Parameter Description Definition and Usage

The mysqli_num_rows() function returns the number of rows in a result


result Required. Specifies a result set identifier set.
returned by mysqli_query(),
mysqli_store_result() or Syntax
mysqli_use_result() mysqli_num_rows(result);

mysqli_num_rows() Function
Parameter Description

15
result Required. Specifies a result set identifier Parameter Description
returned by mysqli_query(),
mysqli_store_result() or
mysqli_use_result() connection Required. Specifies the MySQL connection to
use
mysqli_query() Function

query Required. Specifies the query string


Example Optional. A constant. Either:
resultmode
Perform queries against the database: MYSQLI_USE_RESULT (Use this if
<?php we have to retrieve large amount of
$con=mysqli_connect("localhost","my_user","my_password","my_db"); data)
// Check connection MYSQLI_STORE_RESULT (This is
if (mysqli_connect_errno()) default)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error(); mysqli_real_connect() Function
}

// Perform queries
mysqli_query($con,"SELECT * FROM Persons"); Example
mysqli_query($con,"INSERT INTO Persons
(FirstName,LastName,Age) Open a new connection to the MySQL server:
VALUES ('Glenn','Quagmire',33)"); <?php
$con=mysqli_init();
mysqli_close($con);
if (!$con)
?>
{
Definition and Usage die("mysqli_init failed");
}
The mysqli_query() function performs a query against the database.
if
Syntax
(!mysqli_real_connect($con,"localhost","my_user","my_password","my
mysqli_query(connection,query,resultmode);
_db"))
{

16
die("Connect Error: " . mysqli_connect_error());
}
password Optional. Specifies the MySQL password
mysqli_close($con);
?> dbname Optional. Specifies the default database to be used
Definition and Usage

The mysqli_real_connect() function opens a new connection to the port Optional. Specifies the port number to attempt to
MySQL server. connect to the MySQL server

The mysqli_real_connect() function differs from mysqli_connect() in the


following ways: socket Optional. Specifies the socket or named pipe to be
used
mysqli_real_connect() requires a valid object created
by mysqli_init()
mysqli_real_connect() can be used with mysqli_options() to set flag Optional. Specifies different connection options.
different options for the connection Possible values:
mysqli_real_connect() has a flag parameter
Syntax MYSQLI_CLIENT_COMPRESS - Use
mysqli_real_connect(connection,host,username,password,dbname,port,s compression protocol
ocket,flag); MYSQLI_CLIENT_FOUND_ROWS -
Return number of matched rows (not
affected rows)
MYSQLI_CLIENT_IGNORE_SPACE -
Parameter Description
Allow spaces after function names. Make
function names reserved words
MYSQLI_CLIENT_INTERACTIVE -
connection Required. Specifies the MySQL connection to use
Allow interactive_timeout seconds of
inactivity before closing connection
host Optional. Specifies a host name or an IP address MYSQLI_CLIENT_SSL - Use SSL
encryption

username Optional. Specifies the MySQL username mysqli_real_escape_string() Function

17
Example
Parameter Description
Escape special characters in a string:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db"); connection Required. Specifies the MySQL connection
to use
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error(); escapestring Required. The string to be escaped.
} Characters encoded are NUL (ASCII 0), \n,
\r, \, ', ", and Control-Z.
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>
Definition and Usage

The mysqli_real_escape_string() function escapes special characters in a


string for use in an SQL statement.
Syntax
mysqli_real_escape_string(connection,escapestring);

18

You might also like