Docsity

mysql in php (study slides), Study notes of Programming Languages

Partial preview of the text

Download mysql in php (study slides) and more Study notes Programming Languages in PDF only on Docsity!

PHP MySQL Database

2022 - 2023

What is MySQL?

2 Eng. Hazem A. Alrakhawi

What is MySQL?

  • The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows.
  • Databases are useful for storing information categorically.
  • A company may have a database with the following tables:
  • Employees
  • Products
  • Customers
  • Orders

PHP Connect to MySQL

5 Eng. Hazem A. Alrakhawi

Should I Use MySQLi or PDO?

  • If you need a short answer, it would be "Whatever you like".
  • Both MySQLi and PDO have their advantages:
  • PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
  • So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi , you will need to rewrite the entire code - queries included.

Open a Connection to MySQL

  • You can open a connection and dealing with MySQL by three methods:
  • MySQLi Object-Oriented.
  • MySQLi Procedural.
  • PDO – PHP Data Object.

Example (MySQLi Object-Oriented)

  • Note on the object-oriented example above:
  • $connect_error was broken until PHP 5. 2. 9 and 5. 3. 0. If you need to ensure compatibility with PHP versions prior to 5. 2. 9 and 5. 3. 0 , use the following code instead:
  • // Check connection
  • if (mysqli_connect_error()) {
  • die("Database connection failed: ". mysqli_connect_error());
  • }

Example (MySQLi Procedural)

Close the Connection

  • The connection will be closed automatically when the script ends.
  • To close the connection before, use the following:
  • MySQLi Object-Oriented: $conn->close();
  • MySQLi Procedural: mysqli_close($conn);
  • PDO: $conn = null;

PHP Create a MySQL Database

14 Eng. Hazem A. Alrakhawi

Create Database Using MySQLi Procedural

PHP MySQL Create Table

17 Eng. Hazem A. Alrakhawi

Create a MySQL Table

  • After the data type, you can specify other optional attributes for each column:
  • NOT NULL - Each row must contain a value for that column, null values are not allowed.
  • DEFAULT value - Set a default value that is added when no other value is passed.
  • UNSIGNED - Used for number types, limits the stored data to positive numbers and zero.

Create a MySQL Table

  • AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added.
  • PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT.
  • Each table should have a primary key column (in this case: the "id" column). Its value must be unique for each record in the table.