Professional Documents
Culture Documents
<!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
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
connection Required. Specifies the MySQL dbname Optional. Specifies the default database to
connection to close be used
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);
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);
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();
} }
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 ?>
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
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
// 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
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']);
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Definition and Usage
18