Sie sind auf Seite 1von 20

TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

PHP & MySQL


** Refer to MySQL Improved Extension at
http://php.net/manual/en/book.mysqli.php**
Errors are indicated in some scripts and should apply to the remaining

The following script is a simple PHP script. If this small script runs OK, we have everything
needed installed.

Try the following script by saving as “version1.php”


<?php

$host = "localhost";
$user = "user12"; //give your own username & pwd
Must create user in XAMPP
$pass = "34klq*";
User account
$r = mysqli_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established :";
}

echo mysqli_get_server_info($r);
mysqli_close($r);
?>

We connect to the database and get some info about the MySQL server.

$host = "localhost";
$user = "user12";
$pass = "34klq*";
These are three variables holding the host name, user name and password. The variables are
needed when connecting to the MySQL database.

$r = mysqli_connect($host, $user, $pass);


We use the mysqli_connect() function to connect to the database. The function returns a
boolean value indicating whether the connection was successfully created or not. The function
has 3 parameters. The first is the host, where the server is installed. The second and third
parameters are the user name and user password.

if (!$r) {
echo "Could not connect to server";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established :";
}
Now we check the $r variable. If it contains a boolean false, the connection to the database was
not created. We call the trigger_error() function to generate an error message. The first
generic message goes to the user. The more specific error message generated with the
trigger_error() function is logged.

echo mysqli_get_server_info();
The mysqli_get_server_info() returns the MySQL server version.

mysqli_close();

1
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

The mysqli_close() function closes the connection to the database. Closing connection in our


case is not necessary, as non-persistent open links are automatically closed at the end of the
script's execution. However, it is a good programming practice.

Try the following script by saving as “version2.php”

<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established";
}

$query = "SELECT VERSION()"; //MySQL 4.0


$rs = mysqli_query($r,$query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed";
}

$row = mysqli_fetch_row($rs);
echo "Version: $row[0]";

mysqli_close($r);
?>

We check for the version of the MySQL database. This time using an SQL query.

$query = "SELECT VERSION()";


This is the SQL SELECT statement. It returns the version of the database. The VERSION() is a
built-in MySQL function.

$rs = mysqli_query($r,$query);
The mysqli_query() function executes an SQL query on the database. This is a SELECT query,
so the result is a result set, containing some data.

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed";
}
In case of an error we generate an error message. Otherwise we print the SQL query executed.

$row = mysqli_fetch_row($rs);
We fetch a row from the result set. The $row variable is an array containing data.

echo "Version: $row[0]";

2
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

We print the data from the array. We know from the nature of our query, that we have only one
item it the array, the MySQL version string.

$ php version2.php
Connection established
Query: SELECT VERSION() executed
Version: 10.1.36-MariaDB

Output of the script on my system (output on your system may be different).

3
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Creating and populating a table


Next we are going to create a database table and fill it with data.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

function execute_query($query) { //error


$r = mysqli_query($query); //error
if (!$r) {
echo "Cannot execute query: $query<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}
}

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db); //error


if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "DROP TABLE IF EXISTS Cars";


execute_query($query); //error

$query = "CREATE TABLE Cars(Id INT PRIMARY KEY, Name TEXT, Price INT) ENGINE=InnoDB";
execute_query($query); //error

$query = "INSERT INTO Cars VALUES(1,'Audi',52642)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(2,'Mercedes',57127)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(3,'Skoda',9000)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(4,'Volvo',29000)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(5,'Bentley',350000)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(6,'Citroen',21000)";


execute_query($query); //error

$query = "INSERT INTO Cars VALUES(7,'Hummer',41400)";


execute_query($query); //error

4
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

$query = "INSERT INTO Cars VALUES(8,'Volkswagen',21600)";


execute_query($query); //error

mysqli_close(); //error
?>

In the above code example, we create a Cars table with 8 rows.

function execute_query($query) {
$r = mysqli_query($query);
if (!$r) {
echo "Cannot execute query: $query<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}
}

We have created a custom execute_query() function which will be called for each INSERT
statement.

$r2 = mysqli_select_db($db);
Before we can work with database tables, we must select a database. A database is selected with
a mysqli_select_db() function.

if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}
Error handling for the database selection process.
$query = "DROP TABLE IF EXISTS Cars";
execute_query($query);
The first query drops a Cars table, if it already exists.

$query = "CREATE TABLE Cars(Id INT PRIMARY KEY, Name TEXT, Price INT) ENGINE=InnoDB";
execute_query($query);
This is the SQL statement to create the Cars table.

$query = "INSERT INTO Cars VALUES(1,'Audi',52642)";


execute_query($query);

A car record is inserted into the table.

if (!$ok) {
echo mysqli_error();
die("Cannot execute query. <br />");
}
In case of an error, we print the error message and terminate the script.

$ php create_fill.php
Connection established
Database selected
Query: DROP TABLE IF EXISTS Cars executed

5
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Query: CREATE TABLE Cars(Id INT PRIMARY KEY, Name TEXT,Price INT) ENGINE=InnoDB
executed
Query: INSERT INTO Cars VALUES(1,'Audi',52642) executed
Query: INSERT INTO Cars VALUES(2,'Mercedes',57127) executed
Query: INSERT INTO Cars VALUES(3,'Skoda',9000) executed
Query: INSERT INTO Cars VALUES(4,'Volvo',29000) executed
Query: INSERT INTO Cars VALUES(5,'Bentley',350000) executed
Query: INSERT INTO Cars VALUES(6,'Citroen',21000) executed
Query: INSERT INTO Cars VALUES(7,'Hummer',41400) executed
Query: INSERT INTO Cars VALUES(8,'Volkswagen',21600) executed

Executing the create_fill.php script.


mysql> SELECT * FROM Cars;
+----+------------+--------+
| Id | Name | Price |
+----+------------+--------+
| 1 | Audi | 52642 |
| 2 | Mercedes | 57127 |
| 3 | Skoda | 9000 |
| 4 | Volvo | 29000 |
| 5 | Bentley | 350000 |
| 6 | Citroen | 21000 |
| 7 | Hummer | 41400 |
| 8 | Volkswagen | 21600 |
+----+------------+--------+
8 rows in set (0.00 sec)
The data inserted into the Cars table.

6
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Retrieving data
Now, that we have inserted some data into the database, we want to get it back.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db); //error


if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "SELECT * FROM Cars LIMIT 5";


$rs = mysqli_query($query); //error
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

while ($row = mysqli_fetch_assoc($rs)) {


echo $row['Id'] . " " . $row['Name'] . " " . $row['Price'] . "<br />";
}

mysqli_close(); //error
?>

In this example, we retrieve five rows from the Cars table.

$query = "SELECT * FROM Cars LIMIT 5";


This SQL statement selects 5 rows from the Cars table.

$rs = mysqli_query($query);
We execute the query with the mysqli_query() function and retrieve the result set.

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}
If the query did not succeed, we generate an error message.

while ($row = mysqli_fetch_assoc($rs)) {


echo $row['Id'] . " " . $row['Name'] . " " . $row['Price'] . "<br />";
}

7
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

We loop through the result set and print the data to the console.

The mysqli_fetch_assoc()function returns an associative array of strings that corresponds to


the fetched row, or FALSE if there are no more rows. In other words, the function call returns a
row from the result set. This row is in the form of an associative array. The column names are
keys to the associative array. When there are no more rows in the result set, the function returns
FALSE and the while loop terminates.

$ php query.php
Connection established
Database selected
Query: SELECT * FROM Cars LIMIT 5 executed
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
This is the output of the example.

In the second example, we will fetch data with the mysqli_fetch_row() function.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}
$r2 = mysqli_select_db($db); //error
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "SELECT Id, Name, Price From Cars LIMIT 5";


$rs = mysqli_query($query); //error
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

$nrows = mysqli_num_rows($rs);
for ($i = 0; $i < $nrows; $i++) {
$row = mysqli_fetch_row($rs);
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[1]; //error

8
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

echo "<br />";


}

mysqli_close(); //error
?>

We get the first 5 rows from the Cars table.

$nrows = mysqli_num_rows($rs);
The mysqli_num_row() function gets the number of rows from the result set.

for ($i = 0; $i < $nrows; $i++) {


$row = mysqli_fetch_row($rs);
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[1];
echo "<br />";
}
We use the for loop to iterate over the returned rows. The mysqli_fetch_row() function
retrieves the row from the result set in the form of an enumerated array.

$ php query.php
Connection established
Query: SELECT * FROM Cars LIMIT 5 executed
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
Output.

In the following example, we show how to retrieve a specific row from a table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db); //error


if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$name = "Volkswagen";

9
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

$query = sprintf("SELECT Id, Name, Price From Cars Where Name = '%s'",
mysqli_real_escape_string($name)); //error

$rs = mysqli_query($query); //error


if (!$rs) {
echo "Could not execute query: $query<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

while ($row = mysqli_fetch_object($rs)) {


echo $row->Id;
echo " ";
echo $row->Name;
echo " ";
echo $row->Price;
echo "<br />";
}

mysqli_close(); //error
?>

Developers must take security concerns into account when working with input from users. We
must always process the data sent from outside world. Check for validity of the data.

$name = "Volkswagen";
In the script, we check, if we have "Volkswagen" in the Caras table. This value might come from
an xml file or a web form. We will show, how to check it.

$query = sprintf("SELECT Id, Name, Price From Cars Where Name = '%s'",
mysqli_real_escape_string($name));
We build the SQL statement using the sprintf() function. We process the $name variable with
the mysqli_real_escape_string() function. This function escapes special characters in a
string for use in an SQL statement. This prevents SQL injection attacks and data corruption.
After the variable was processed, it is put into the SQL statement string.

while ($row = mysqli_fetch_object($rs)) {


echo $row->Id;
echo " ";
echo $row->Name;
echo " ";
echo $row->Price;
echo "<br />";
}
We fetch the data using the mysqli_fetch_object() function. The function fetches a result
row as an object. And we use the object notation to get the table columns.

$ php query3.php
Connection established
Database selected
Query: SELECT Id, Name, Price From Cars Where Name = 'Volkswagen' executed
8 Volkswagen 21600
The output of the example. We found the car and printed the whole row to the console.

10
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Escaping characters
We will have a small example demonstrating how to escape characters. There are some
characters which are considered to be unsafe in a database environment. One of them is a single
quote character.
mysql> CREATE TABLE IF NOT EXISTS Authors(Id INT PRIMARY KEY AUTO_INCREMENT,
-> Name VARCHAR(25)) ENGINE=InnoDB;
Query OK, 0 rows affected (0.09 sec)
For the example, we create an Authors table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db); //error

if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$name = "O'Neill";
$name_es = mysqli_real_escape_string($name); //error

$query = "INSERT INTO Authors(Name) VALUES('$name_es')";


$rs = mysqli_query($query); //error

if (!$rs) {
echo "Could not execute query: $query<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

mysqli_close(); //error
?>

We insert a new author to the Authors table. The name of the author is O'Neill. The name has an
unsafe single quote character.

$name_es = mysqli_real_escape_string($name);
Thay is why we use the mysqli_real_escape_string() function to escape this character.

$query = "INSERT INTO Authors(Name) VALUES('$name_es')";


$rs = mysqli_query($query);
We create the statement and execute it.

11
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

mysql> SELECT * FROM Authors;


+----+---------+
| Id | Name |
+----+---------+
| 1 | O'Neill |
+----+---------+
1 row in set (0.00 sec)
The name has been successfully written to the table.

12
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Column headers
Next we will show, how to print column headers with the data from the database table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "SELECT * From Cars LIMIT 8";


$rs = mysqli_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

$cname1 = mysqli_fetch_field($rs, 0);


$cname2 = mysqli_fetch_field($rs, 1);
$cname3 = mysqli_fetch_field($rs, 2);

printf("%3s %-11s %8s<br />", $cname1->name, $cname2->name,


$cname3->name);

while ($row = mysqli_fetch_row($rs)) {


printf("%3s %-11s %8s<br />", $row[0], $row[1], $row[2]);
}

mysqli_close();
?>

Again, we print the contents of the Writers table to the console. Now, we include the names of
the columns too.

$cname1 = mysqli_fetch_field($rs, 0);


$cname2 = mysqli_fetch_field($rs, 1);
$cname3 = mysqli_fetch_field($rs, 2);
To get a specific field name, we utilize the mysqli_fetch_field() function. The function return
an object containing column information.

printf("%3s %-11s %8s<br />", $cname1->name, $cname2->name,$cname3->name);


The column names are printed and formatted. The name property contains the column name.

13
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

$ php columns.php
Connection established
Database selected
Query: SELECT * From Cars LIMIT 8 executed
Id Name Price
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
6 Citroen 21000
7 Hummer 41400
8 Volkswagen 21600
Ouput of the script.

14
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Fields, rows
The following script counts the number of fields/columns and rows returned by a query.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "SELECT * FROM Cars WHERE Id IN (1, 2, 3)";


$rs = mysqli_query($query);
if (!$rs) {
echo "Could not execute query: $query<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

echo "We have " . mysqli_num_fields($rs) . " fields<br />";


echo "We have " . mysqli_num_rows($rs) . " rows<br />";

print_r(mysqli_fetch_row($rs));

mysqli_close();
?>

We select three rows from the Cars table. We count the number of rows and columns returned
by a query.

$query = "SELECT * FROM Cars WHERE Id IN (1, 2, 3)";


This is the query to be executed. It selects first three rows from the Cars table.

echo "We have " . mysqli_num_fields($rs) . " fields<br />";


The mysqli_num_fields() returns the number of fields returned by a query.

echo "We have " . mysqli_num_rows($rs) . " rows<br />";


The mysqli_num_rows() returns the number of rows returned by a query.
print_r(mysqli_fetch_row($rs));
We print the contents of the array.

$ php fields_rows.php
Connection established
Database selected

15
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Query: SELECT * FROM Cars WHERE Id IN (1, 2, 3) executed


We have 3 fields
We have 3 rows
Array
(
[0] => 1
[1] => Audi
[2] => 52642
)
Running the script.

16
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Writing images
Some people prefer to put their images into the database, some prefer to keep them on the file
system for their applications. Technical difficulties arise when we work with millions of images.
Images are binary data. MySQL database has a special data type to store binary data
calledBLOB (Binary Large Object).

mysql> CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
Query OK, 0 rows affected (0.06 sec)
For this example, we create a new table called Images.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($r,$db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$file = "woman.jpg";
$img = fopen($file, 'r');
if (!$img) {
echo "Cannot open file for writing<br />";
trigger_error("Cannot open file for writing<br />", E_USER_ERROR);
}

$data = fread($img, filesize($file));


if (!$data) {
echo "Cannot read image data<br />";
trigger_error("Cannot read image data<br />", E_USER_ERROR);
}

$es_data = mysqli_real_escape_string($data);
fclose($img);

$query = "INSERT INTO Images(Id, Data) Values(1, '$es_data')";


$rs = mysqli_query($r,$query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query successfully executed<br />";
}

mysqli_close($r);
?>

17
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

In the above script, we read a jpg image and insert it into the Images table.

$file = "woman.jpg";
This is the image name, that we read from the filesystem and write into the database. It is
located in the same directory as the script name.

$img = fopen($file, 'r');

if (!$img) {
echo "Cannot open file for writing<br />";
trigger_error("Cannot open file for writing<br />", E_USER_ERROR);
}

$data = fread($img, filesize($file));

if (!$data) {
echo "Cannot read image data<br />";
trigger_error("Cannot read image data<br />", E_USER_ERROR);
}
We open and read the image. The fread() function returns the data as string.

$es_data = mysqli_real_escape_string($data);
We escape unsafe characters.

fclose($img);
We close the handle to the image file.

$query = "INSERT INTO Images(Id, Data) Values(1, '$es_data')";

$rs = mysqli_query($r,$query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query successfully executed<br />";
}
We insert the data to the newly created Images table.

18
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

Reading images
In the previous example, we have inserted an image into the database table. Now we are going to
read the image back from the table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysqli_connect($host, $user, $pass);


if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}

$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}

$query = "SELECT Data FROM Images WHERE Id=1";


$rs = mysqli_query($r,$query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Query: $query executed<br />";
}

$row = mysqli_fetch_row($rs);

$file = "woman2.jpg";
$img = fopen($file, 'wb');
if (!$img) {
echo "Cannot open file for writing<br />";
trigger_error("Cannot open file for writing<br />", E_USER_ERROR);
}

$r3 = fwrite($img, $row[0]);


if (!$r3) {
echo "Cannot write image to file<br />";
trigger_error("Cannot write image to file<br />", E_USER_ERROR);
}

fclose($img);

mysqli_close($r);
?>

We read one image from the Images table.

$query = "SELECT Data FROM Images WHERE Id=1";


We select one record from the table.

$row = mysqli_fetch_row($rs);

19
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020

We fetch one row from the result set. There is only one row, containing the image data.

$file = "woman2.jpg";
We will create a new image file name called "woman2.jpg".

$img = fopen($file, 'wb');

if (!$img) {
echo "Cannot open file for writing<br />";
trigger_error("Cannot open file for writing<br />", E_USER_ERROR);
}
We open a writable binary file.
$r3 = fwrite($img, $row[0]);

if (!$r3) {
echo "Cannot write image to file<br />";
trigger_error("Cannot write image to file<br />", E_USER_ERROR);
}
We write the data to the filesystem using the fwrite() function.

Now we should have an image called "woman2.jpg" in our current directory. We can check if it is
the same image, that we have inserted into the table.

20

Das könnte Ihnen auch gefallen