Professional Documents
Culture Documents
Eyad Alshareef
Eyad Alshareef
19.9 Reading from a Database
Parameter Description
Eyad Alshareef
2 - Selecting a Database
Once you establish a connection with a database server then it is required to select a
particular database where your all the tables are associated.
PHP provides function mysqli_select_db to select a database. It returns TRUE on success
or FALSE on failure.
Parameter Description
db_name Required - Database name to be selected
connection Required - if not specified then last opend
connection by mysql_connect will be used.
Eyad Alshareef
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname); // ----- 1+2
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
mysqli_close($conn); // ------ 5
}
?>
Eyad Alshareef
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password); // ----- 1
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
$DataBase = mysqli_select_db ($conn , $db); // ------2
mysqli_close($conn); // ------ 5
}
?>
Eyad Alshareef
3 – Execute a Query
Parameter Description
sql Required - SQL query to execute
bool mysql_query( sql, connection );
connection Required - if not specified then last opend
connection by mysql_connect will be used.
Eyad Alshareef
Queries types
Create a database
$sql = 'CREATE Database test_db';
Creating Database Tables:
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 ))';
<?php
$result = mysqli_query($conn , "SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysqli_error($conn);
exit;
}
$row = mysqli_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Eyad Alshareef
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
Eyad Alshareef
$result = mysqli_query($Conn , $sql2);
while ($row = mysqli_fetch_row($result))
{
foreach ($row as $key => $value )
print $value."<br>";
}
Eyad Alshareef
5-Closing Database Connection:
Eyad Alshareef
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.
©1992-2012 by Pearson Education, Inc. All Rights Reserved.