Beruflich Dokumente
Kultur Dokumente
The following script is a simple PHP script. If this small script runs OK, we have everything
needed installed.
$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.
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
<?php
$host = "localhost";
$user = "user12";
$pass = "34klq*";
$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.
$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.
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
3
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020
$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";
$query = "CREATE TABLE Cars(Id INT PRIMARY KEY, Name TEXT, Price INT) ENGINE=InnoDB";
execute_query($query); //error
4
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020
mysqli_close(); //error
?>
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.
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
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";
mysqli_close(); //error
?>
$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.
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.
$ 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";
$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
mysqli_close(); //error
?>
$nrows = mysqli_num_rows($rs);
The mysqli_num_row() function gets the number of rows from the result set.
$ 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";
$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
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.
$ 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";
if (!$r) {
echo "Could not connect to server<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Connection established<br />";
}
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
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.
11
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020
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";
$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<br />";
}
mysqli_close();
?>
Again, we print the contents of the Writers table to the console. Now, we include the names of
the columns too.
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";
$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<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.
$ php fields_rows.php
Connection established
Database selected
15
TMS2828 / TMN2234/ TMT/TMP 2654 Web-based System Development S2 2019/2020
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";
$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);
}
$es_data = mysqli_real_escape_string($data);
fclose($img);
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.
if (!$img) {
echo "Cannot open file for writing<br />";
trigger_error("Cannot open file for writing<br />", E_USER_ERROR);
}
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.
$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";
$r2 = mysqli_select_db($db);
if (!$r2) {
echo "Cannot select database<br />";
trigger_error(mysqli_error(), E_USER_ERROR);
} else {
echo "Database selected<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);
}
fclose($img);
mysqli_close($r);
?>
$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".
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