Wednesday, April 23, 2025

MySQLi Multiple Insert

multiple_inserts.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";
$database = "address_book";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password, $database);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull <br>";
}

//SQL Command
$sql_command = "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'John', 'Smith', 555777, 'mailx@server.net', 'Main Road 12a');";

$sql_command .= "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'Samantha', 'Smith', 111222, 'mailz@server.net', 'Main Road 12a');";

$sql_command .= "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'Anabela', 'Smith', 555777, 'mailx@server.net', 'Main Road 12a')";

//Check SQL Command
if (mysqli_multi_query($connection, $sql_command)) {
	$last_entry = mysqli_insert_id($connection);
	echo "SQL Command OK, Last ID: " . $last_entry . "<hr>" ;
} else {
	echo "SQL ERROR" . mysqli_error($connection);
}

?>

This PHP code creates a SQL command that inserts multiple rows into the people table of the currently selected database.

The $sql_command variable is a string that concatenates multiple INSERT statements together.

Each INSERT statement specifies the columns and values to be inserted into the table. The id column is set to NULL, which will automatically generate a new value for this column using the AUTO_INCREMENT feature.

The mysqli_multi_query() function is used to execute the SQL command. If the command is successful, the mysqli_insert_id() function is used to retrieve the ID of the last inserted row.

The output will be either "SQL Command OK, Last ID: [ID]" if the command was successful or "SQL ERROR" if there was an error executing the command.

After we run it multiple times:


Connection Successfull
SQL Command OK, Last ID: 24

MySQLi Insert Into

insert_into_table.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";
$database = "address_book";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password, $database);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull <br>";
}

//SQL Command
$sql_command = "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'Samantha', 'Fox', 555444, 'mail@server.com', 'Main Road 12a')";

//Check SQL Command
if (mysqli_query($connection, $sql_command)) {
	echo "SQL Command OK";
} else {
	echo "SQL ERROR" . mysqli_error($connection);
}

?>

This PHP command will execute an SQL INSERT statement to insert a new row into the 'people' table of a MySQL database. The values for each column are provided in the VALUES clause:

  • id: Since it is set to NULL, the auto-increment feature of the 'id' column will automatically generate a new unique value for this row.
  • name: The value 'Samantha' will be inserted into the 'name' column.
  • lastname: The value 'Fox' will be inserted into the 'lastname' column.
  • telephon: The value 555444 will be inserted into the 'telephon' column.
  • email: The value 'mail@server.com' will be inserted into the 'email' column.
  • address: The value 'Main Road 12a' will be inserted into the 'address' column.

If the INSERT statement executes successfully, the code will output the message "SQL Command OK". Otherwise, if there is an error, the code will output "SQL ERROR" followed by the error message returned by MySQL.

After First Run, One Row is in Table. You can run it multiple times.


Connection Successfull
SQL Command OK

MySQLi Create Table

create_table.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";
$database = "address_book";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password, $database);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull <br>";
}

//SQL Command
$sql_command = "CREATE TABLE people(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
telephon INT,
email VARCHAR(100),
address VARCHAR(100),
meta TIMESTAMP
)";

//Check SQL Command
if (mysqli_query($connection, $sql_command)) {
	echo "SQL Command OK";
} else {
	echo "SQL ERROR" . mysqli_error($connection);
}

?>

This PHP code creates a new table named "people" in the currently selected MySQL database using the "CREATE TABLE" SQL command. The "people" table has 7 columns: "id", "name", "lastname", "telephon", "email", "address", and "meta".

The "id" column is of type INT, NOT NULL, and serves as the primary key of the table. The "name" and "lastname" columns are of type VARCHAR(30) and are also NOT NULL. The "telephon" column is of type INT and can contain phone numbers. The "email" column is of type VARCHAR(100) and can contain email addresses. The "address" column is of type VARCHAR(100) and can contain physical addresses. The "meta" column is of type TIMESTAMP and will automatically update every time a row is added or modified.

The code first stores the SQL command in the variable $sql_command. It then uses the mysqli_query function to execute the command on the MySQL database. If the query is successful, the code outputs "SQL Command OK". If there is an error, the code outputs "SQL ERROR" followed by a message describing the error returned by mysqli_error($connection).

After First Run:


Connection Successfull
SQL Command OK

After Second Run:


Connection Successfull
SQL ERROR Table 'people' already exists

MySQLi Create Database

create_database.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull <br>";
}

//SQL Command
$sql_command = "CREATE DATABASE address_book";

//Check SQL Command
if (mysqli_query($connection, $sql_command)) {
	echo "DATABASE CREATED";
} else {
	echo "SQL ERROR" . mysqli_error($connection);
}

?>

This code is creating a new MySQL database named "address_book" using the mysqli_query() function. Here is what each line of the code does:

  1. $sql_command = "CREATE DATABASE address_book"; - This line defines a SQL command that will create a new database named "address_book".
  2. if (mysqli_query($connection, $sql_command)) { - This line checks if the SQL command was successfully executed using the mysqli_query() function. The $connection variable holds the connection object to the MySQL server that was established earlier.
  3. echo "DATABASE CREATED"; - This line will be printed to the screen if the database creation is successful.
  4. else { echo "SQL ERROR" . mysqli_error($connection); } - If the SQL command fails, this line will be executed and will print an error message that includes the error message returned by the mysqli_error() function.

After first run:


Connection Successfull
DATABASE CREATED

After second run:


Connection Successfull
SQL ERROR Can't create database 'address_book'; database exists

MySQLi Server Connection

server_connection.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password);

//Check Connection
if (!$connection) {
	echo "Check Config, or is Server Alive ?";
} else {
	echo "Connection Successfull";
}

?>
  • $server = "localhost";: This line defines a variable $server and sets its value to "localhost". This variable holds the hostname of the MySQL server.
  • $user = "root";: This line defines a variable $user and sets its value to "root". This variable holds the username to access the MySQL server.
  • $password = "";: This line defines a variable $password and sets its value to "". This variable holds the password to access the MySQL server.
  • $connection = mysqli_connect($server, $user, $password);: This line establishes a connection to the MySQL server using the mysqli_connect() function, which is provided by the MySQLi extension. It takes three parameters - $server, $user, and $password - which contain the hostname, username, and password to connect to the server. The function returns a connection object if the connection is successful, otherwise it returns false. The connection object is assigned to a variable $connection.
  • if (!$connection) {: This line starts an if statement that checks whether the connection was successful or not. The ! operator negates the value of $connection, so if $connection is false, the condition evaluates to true.
  • echo "Check Config, or is Server Alive ?";: This line prints an error message to the screen if the connection was not successful.
  • } else {: This line marks the beginning of the else block, which is executed if the connection was successful.
  • echo "Connection Successfull";: This line prints a success message to the screen if the connection was successful.
  • }: This line marks the end of the if-else block.

server_connection_with_dedicated_check.php


<?php
//Config

$server = "localhost";
$user = "root";
$password = "";

//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password);

//Check Connection
if (!$connection) {
	die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
	echo "Connection Successfull";
}

?>
  1. if (!$connection) {: This line starts an if statement that checks if the connection was unsuccessful. The ! operator is used to check if the value of $connection is false.

  2. die("<h2>Total Fail</h2> " . mysqli_connect_error());: This line prints an error message and stops the execution of the script if the connection was unsuccessful. The die() function is used to print the error message and exit the script. The mysqli_connect_error() function is used to retrieve the error message from the most recent MySQL connection error.

  3. echo "Connection Successfull";: This line prints a success message if the connection was successful. The echo statement is used to output the message to the web page.

MySQLi Introduction

The MySQLi functions allows you to access MySQL database servers using PHP. 

First, you must have MySQL server installed on your machine, or you can use remote MySQLserver, on some development/testing machine.

Also, you can install stand alone MySQL sever, or get "full package" with Easy PHP or similar solutions.

It's not hard, but you must be precise.

You are strongly advised to check corresponding Youtube video to understand installation, webserver dashboard and MySQL Server setup.

MySQL DEFAULT Values

A default value is a value that is assigned to a column if no explicit value is provided during insertion.

It is useful if the user does not know what value to provide. 

The default value can be specified during the column definition, or it can be added later using the ALTER TABLE statement.  

What is in our table:

mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
|    9 | XXX    | XXX_1      | Some            |      4562 |   500 |
+------+--------+------------+-----------------+-----------+-------+
9 rows in set (0.00 sec)

mysql>
Now we will add a new column called ShipCorp to the Stores table and sets the default value to 'Speedy Gonzales'.
mysql> ALTER TABLE Stores ADD ShipCorp VARCHAR (50) DEFAULT 'Speedy Gonzales';
Query OK, 0 rows affected (0.74 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

This means that if a new row is inserted into the Stores table without specifying a value for ShipCorp, the default value 'Speedy Gonzales' will be used instead. 


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+-----------------+
| s_id | city   | store_name | product         | available | price | ShipCorp        |
+------+--------+------------+-----------------+-----------+-------+-----------------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 | Speedy Gonzales |
|    2 | London | London_2   | Gold PSU        |        75 |   100 | Speedy Gonzales |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 | Speedy Gonzales |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 | Speedy Gonzales |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 | Speedy Gonzales |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 | Speedy Gonzales |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 | Speedy Gonzales |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 | Speedy Gonzales |
|    9 | XXX    | XXX_1      | Some            |      4562 |   500 | Speedy Gonzales |
+------+--------+------------+-----------------+-----------+-------+-----------------+
9 rows in set (0.00 sec)

mysql>

New row:


mysql> INSERT INTO Stores(s_id, city, store_name, product, available, price)
    -> VALUES (NULL, 'xxx', 'yyy', 'ppp', 5421, 500);
Query OK, 1 row affected (0.07 sec)

mysql>

Our MySQL code inserts a new row into the "Stores" table with the following values for each column:

  • "s_id": NULL (since it is an auto-increment column, the database will generate a unique value for this column automatically)
  • "city": 'xxx'
  • "store_name": 'yyy'
  • "product": 'ppp'
  • "available": 5421
  • "price": 500

The statement is successful and affects 1 row, as confirmed by the message "Query OK, 1 row affected". 


mysql> SELECT * FROM Stores WHERE s_id=10;
+------+------+------------+---------+-----------+-------+-----------------+
| s_id | city | store_name | product | available | price | ShipCorp        |
+------+------+------------+---------+-----------+-------+-----------------+
|   10 | xxx  | yyy        | ppp     |      5421 |   500 | Speedy Gonzales |
+------+------+------------+---------+-----------+-------+-----------------+
1 row in set (0.00 sec)

mysql>

Our select instruction code gets all columns from the "Stores" table where the value of the "s_id" column is equal to 10. 

The result is a table with one row that matches the condition, showing the values of all columns in that row. 

mysql> ALTER TABLE Stores ALTER ShipCorp SET DEFAULT 'Daffy Duck';
Query OK, 0 rows affected (0.14 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

We can change the default value of the "ShipCorp" column in the "Stores" table to 'Daffy Duck'. 

This means that if a new row is inserted into the "Stores" table without specifying a value for the "ShipCorp" column, it will be automatically set to 'Daffy Duck'.

Note that this change does not affect existing rows in the table - it only affects future inserts.

If you want to update the "ShipCorp" value for existing rows that do not have a value specified, you can use the UPDATE statement with a WHERE clause that checks for NULL values in the "ShipCorp" column. 


mysql> DESCRIBE Stores;
+------------+-------------+------+-----+------------+----------------+
| Field      | Type        | Null | Key | Default    | Extra          |
+------------+-------------+------+-----+------------+----------------+
| s_id       | int         | NO   | PRI | NULL       | auto_increment |
| city       | varchar(30) | YES  |     | NULL       |                |
| store_name | varchar(30) | YES  |     | NULL       |                |
| product    | varchar(50) | YES  |     | NULL       |                |
| available  | int         | YES  |     | NULL       |                |
| price      | int         | YES  |     | NULL       |                |
| ShipCorp   | varchar(50) | YES  |     | Daffy Duck |                |
+------------+-------------+------+-----+------------+----------------+
7 rows in set (0.00 sec)

mysql>

New row:


mysql> INSERT INTO Stores(s_id, city, store_name, product, available, price)
    -> VALUES (NULL, 'bla', 'bla', 'bla', 1234, 350);
Query OK, 1 row affected (0.09 sec)

mysql>

The above code is inserting a new row into the "Stores" table with the following values:

  • s_id: NULL (which will auto-increment since s_id is an auto-increment column)
  • city: 'bla'
  • store_name: 'bla'
  • product: 'bla'
  • available: 1234
  • price: 350

Since the "ShipCorp" column has a default value set as 'Daffy Duck', it will automatically be set to that value for this new row. 

Check row 11, it's there.


mysql> SELECt * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+-----------------+
| s_id | city   | store_name | product         | available | price | ShipCorp        |
+------+--------+------------+-----------------+-----------+-------+-----------------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 | Speedy Gonzales |
|    2 | London | London_2   | Gold PSU        |        75 |   100 | Speedy Gonzales |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 | Speedy Gonzales |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 | Speedy Gonzales |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 | Speedy Gonzales |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 | Speedy Gonzales |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 | Speedy Gonzales |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 | Speedy Gonzales |
|    9 | XXX    | XXX_1      | Some            |      4562 |   500 | Speedy Gonzales |
|   10 | xxx    | yyy        | ppp             |      5421 |   500 | Speedy Gonzales |
|   11 | bla    | bla        | bla             |      1234 |   350 | Daffy Duck      |
+------+--------+------------+-----------------+-----------+-------+-----------------+
11 rows in set (0.00 sec)

mysql>

MySQL ALTER TABLE and DELETE Columns

The ALTER TABLE statement is used to modify the structure of an existing table, such as adding or dropping columns, changing column data types or constraints, renaming the table, or changing the table engine.  

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

Our ALTER statement is adding a new column named "Manager" to the "Stores" table in the MySQL database, with a data type of VARCHAR (variable character) and a maximum length of 50 characters. 


mysql> ALTER TABLE Stores ADD COLUMN Manager VARCHAR (50);
Query OK, 0 rows affected (0.58 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

The "ALTER TABLE" command allows you to modify the structure of an existing table in a database.

mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+---------+
| s_id | city   | store_name | product         | available | price | Manager |
+------+--------+------------+-----------------+-----------+-------+---------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 | NULL    |
|    2 | London | London_2   | Gold PSU        |        75 |   100 | NULL    |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 | NULL    |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 | NULL    |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 | NULL    |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 | NULL    |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 | NULL    |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 | NULL    |
+------+--------+------------+-----------------+-----------+-------+---------+
8 rows in set (0.00 sec)

mysql>

Ok, now our MySQL query uses the ALTER TABLE statement to modify the Stores table by changing the data type of the Manager column to VARCHAR(100)


mysql> ALTER TABLE Stores CHANGE Manager Manager VARCHAR (100);
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

The new data type specification indicates that the Manager column can now store character strings up to 100 characters in length. 

The query reports that 0 rows were affected, which means that the table structure was updated successfully without modifying any existing data. 

Structure:


mysql> DESCRIBE Stores;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| s_id       | int          | NO   | PRI | NULL    | auto_increment |
| city       | varchar(30)  | YES  |     | NULL    |                |
| store_name | varchar(30)  | YES  |     | NULL    |                |
| product    | varchar(50)  | YES  |     | NULL    |                |
| available  | int          | YES  |     | NULL    |                |
| price      | int          | YES  |     | NULL    |                |
| Manager    | varchar(100) | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
7 rows in set (0.06 sec)

mysql>

We will use the INSERT INTO statement to add a new record to the Stores table. 


mysql> INSERT INTO Stores
    -> VALUES (NULL, 'XXX', 'XXX_1', 'Some', 4562, 500, "John Smith");
Query OK, 1 row affected (0.09 sec)

mysql>

The NULL value in the s_id column indicates that this value will be automatically generated by MySQL. 

The remaining values represent the data for the new record, including the city, store name, product, available quantity, price, and manager name. 

The query reports that 1 row was affected, indicating that the new record was successfully added to the table.


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+------------+
| s_id | city   | store_name | product         | available | price | Manager    |
+------+--------+------------+-----------------+-----------+-------+------------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 | NULL       |
|    2 | London | London_2   | Gold PSU        |        75 |   100 | NULL       |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 | NULL       |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 | NULL       |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 | NULL       |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 | NULL       |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 | NULL       |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 | NULL       |
|    9 | XXX    | XXX_1      | Some            |      4562 |   500 | John Smith |
+------+--------+------------+-----------------+-----------+-------+------------+
9 rows in set (0.00 sec)

mysql>

Drop column:


mysql> ALTER TABLE Stores DROP COLUMN Manager;
Query OK, 0 rows affected (2.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

This MySQL query uses the ALTER TABLE statement to remove the Manager column from the Stores table. 

Situation after drop column command:

mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
|    9 | XXX    | XXX_1      | Some            |      4562 |   500 |
+------+--------+------------+-----------------+-----------+-------+
9 rows in set (0.00 sec)

mysql>

Add column:


mysql> ALTER TABLE Stores ADD COLUMN BLABLA CHAR(100);
Query OK, 0 rows affected (0.39 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

Drop column:


mysql> ALTER TABLE Stores DROP COLUMN BLABLA;
Query OK, 0 rows affected (1.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

Table structure at the moment:


mysql> DESCRIBE Stores;
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| s_id       | int         | NO   | PRI | NULL    | auto_increment |
| city       | varchar(30) | YES  |     | NULL    |                |
| store_name | varchar(30) | YES  |     | NULL    |                |
| product    | varchar(50) | YES  |     | NULL    |                |
| available  | int         | YES  |     | NULL    |                |
| price      | int         | YES  |     | NULL    |                |
+------------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql>

MySQL HAVING Clause

The MySQL HAVING clause is used to filter the results of an SQL query that includes a GROUP BY clause. 

It allows you to specify a condition that must be met by the groups that are created by the GROUP BY clause.

The HAVING clause is similar to the WHERE clause, but while the WHERE clause is used to filter individual rows, the HAVING clause filters groups of rows. 

The HAVING clause is always used after the GROUP BY clause in a SELECT statement.

The GROUP BY clause in MySQL is used to group together rows in a table based on one or more columns - it is typically used in combination with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX(), which are used to perform calculations on the grouped data. 

What we have in a table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

Simple "HAWING" and  "WERE" combination: 


mysql> SELECT * FROM Stores
    -> WHERE price > 50
    -> HAVING available > 50;
+------+--------+------------+----------+-----------+-------+
| s_id | city   | store_name | product  | available | price |
+------+--------+------------+----------+-----------+-------+
|    1 | London | London_1   | Gold PSU |       153 |   100 |
|    2 | London | London_2   | Gold PSU |        75 |   100 |
+------+--------+------------+----------+-----------+-------+
2 rows in set (0.02 sec)

mysql>

Our query selects all columns from the "Stores" table where the "price" column is greater than 50. 

Then, the HAVING clause is used to further filter the results to only include records where the "available" column is greater than 50.

So, WHERE clause is used to filter individual rows based on a specific condition, and the HAVING clause is used to filter groups of rows based on a specific condition.

mysql> SELECT * FROM Stores
    -> WHERE store_name LIKE "%on%"
    -> HAVING price > 25;
+------+--------+------------+----------+-----------+-------+
| s_id | city   | store_name | product  | available | price |
+------+--------+------------+----------+-----------+-------+
|    1 | London | London_1   | Gold PSU |       153 |   100 |
|    2 | London | London_2   | Gold PSU |        75 |   100 |
+------+--------+------------+----------+-----------+-------+
2 rows in set (0.00 sec)

mysql>

The query selects all columns from the "Stores" table where the "store_name" column contains the string "on". 

Then, the HAVING clause is used to further filter the results to only include records where the "price" column is greater than 25.

MySQL VIEWs

MySQL views are virtual tables that are created based on the result of a SELECT query

In other words, a view is a stored query that you can treat as a table. When you create a view, you define the SELECT statement that will be used to populate the view.

The main purpose of views is to simplify the complexity of a database by allowing users to access only the information they need, without giving them direct access to the underlying tables. 

Views can also be used to combine data from multiple tables or to restrict access to sensitive data.

Once a view is created, you can query it just like any other table, using SELECT statements

MySQL views can be created using the CREATE VIEW statement, and can be modified or dropped using the ALTER VIEW and DROP VIEW statements, respectively. 

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

CREATE VIEW example:


mysql> CREATE VIEW Prices_Higher_Than_100 AS
    -> SELECT store_name, product, available, price
    -> FROM Stores
    -> WHERE Price > 100;
Query OK, 0 rows affected (0.42 sec)

mysql>

The query creates a view named "Prices_Higher_Than_100" that selects data from a table named "Stores". 

The view includes four columns: "store_name", "product", "available", and "price". 

The view only includes records where the "price" column is greater than 100.

Once this view is created, it can be queried like any other table in the database. 

Tables in our database, with our view:


mysql> SHOW TABLES FROM Corp;
+------------------------+
| Tables_in_corp         |
+------------------------+
| documents              |
| internalcontrol        |
| prices_higher_than_100 |
| stores                 |
+------------------------+
4 rows in set (0.02 sec)

mysql>

In this case, there are four tables: "documents", "internalcontrol", "prices_higher_than_100", and "stores".

This command is useful to quickly get an overview of the tables in a database, and to ensure that a particular table or view exists before executing queries or commands that reference it.

When we run our view:


mysql> SELECT * FROM prices_higher_than_100;
+------------+-----------+-----------+-------+
| store_name | product   | available | price |
+------------+-----------+-----------+-------+
| Berlin_1   | Green PSU |        50 |   120 |
+------------+-----------+-----------+-------+
1 row in set (0.00 sec)

mysql>

The query retrieves all records from the view, which only includes records where the "price" column is greater than 100.

The result set returned by the query includes one record that matches the criteria specified in the view's SELECT statement. The values in these columns correspond to the data in the underlying "Stores" table, but only for records where the "price" column is greater than 100.

Our query demonstrates how views can be used to simplify database access and retrieve only the data that meets specific criteria.

MySQL LENGTH Function

The MySQL LENGTH function returns the number of characters in a given string.

It takes a string as an argument and returns an integer value that represents the length of the string.  

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

We need to give name to our LENGTH instruction:


mysql> SELECT product, LENGTH(product) AS NumberOfCharacters FROM Stores;
+-----------------+--------------------+
| product         | NumberOfCharacters |
+-----------------+--------------------+
| Gold PSU        |                  8 |
| Gold PSU        |                  8 |
| Green PSU       |                  9 |
| XYZ Motherboard |                 15 |
| Extension Cable |                 15 |
| LPT Cables      |                 10 |
| COM Cables      |                 10 |
| NIC             |                  3 |
+-----------------+--------------------+
8 rows in set (0.00 sec)

mysql>

Instruction will select the product column and calculate the number of characters in each value using the LENGTH() function. 

The result shows the name of each product in the product column and the length of the name in the NumberOfCharacters column.

Simple.

MySQL MID Function

The MID function in MySQL is used to extract a portion of a string or a substring starting from a specific position with a specified length.

The syntax for the MID function is as follows: 

MID(str, start, length)

Here:

  1. str is the string from which we want to extract a portion.
  2. start is the position from which we want to start extracting the substring. The first position in a string is 1.
  3. length is the number of characters to be extracted from the given string.

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

MID instruction example:


mysql> SELECT MID(product, 1, 3) AS First3Report
    -> FROm Stores;
+--------------+
| First3Report |
+--------------+
| Gol          |
| Gol          |
| Gre          |
| XYZ          |
| Ext          |
| LPT          |
| COM          |
| NIC          |
+--------------+
8 rows in set (0.00 sec)

mysql>

Our code select the first three characters of the "product" column from the "Stores" table and gives it an alias "First3Report". 

Not really useful, but why not:


mysql> SELECT MID(city, 2, 4) AS WeirdReport FROm Stores;
+-------------+
| WeirdReport |
+-------------+
| ondo        |
| ondo        |
| erli        |
| erli        |
| osco        |
| osco        |
| iami        |
| aris        |
+-------------+
8 rows in set (0.00 sec)

mysql>

In this case, the starting position is 2, so the function will skip the first character of each city name. 

The length of the substring is 4, so the function will return the next four characters of each city name. The resulting column is given the alias "WeirdReport".

The output of this code shows the resulting substring of each city name for each row in the table.

MySQL Tutorial - UCASE & LCASE Functions

UCASE() and LCASE() are functions in MySQL used to convert strings to uppercase and lowercase, respectively.

The UCASE() function takes a string as an argument and returns the uppercase version of the string. 

For example: 

SELECT UCASE('hello world') AS UpperCaseString;

This will return the string "HELLO WORLD".

The LCASE() function takes a string as an argument and returns the lowercase version of the string. For example: 

SELECT LCASE('Hello World') AS LowerCaseString;

This will return the string "hello world".

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

UCASE usage:


mysql> SELECT UCASE(product) AS Products FROM Stores;
+-----------------+
| Products        |
+-----------------+
| GOLD PSU        |
| GOLD PSU        |
| GREEN PSU       |
| XYZ MOTHERBOARD |
| EXTENSION CABLE |
| LPT CABLES      |
| COM CABLES      |
| NIC             |
+-----------------+
8 rows in set (0.02 sec)

mysql>

Our code executes a SELECT statement on the "Stores" table in MySQL. The query uses the UCASE() function to convert the values in the "product" column to uppercase, and renames the resulting column as "Products" using the AS keyword.

The resulting "Products" column contains the same values as the "product" column, but with all letters converted to uppercase. 

LCASE usage:


mysql> SELECT LCASE(product) AS Products FROM Stores;
+-----------------+
| Products        |
+-----------------+
| gold psu        |
| gold psu        |
| green psu       |
| xyz motherboard |
| extension cable |
| lpt cables      |
| com cables      |
| nic             |
+-----------------+
8 rows in set (0.00 sec)

mysql>

The LCASE() function is a MySQL string function that converts a string to lowercase

Here, it is applied to the "product" column of the "Stores" table, which contains strings representing product names in uppercase, and returns their lowercase equivalents in the "Products" column of the query result.

MySQL Tutorial - SUM() Function

The MySQL SUM() function is used to calculate the sum of values in a given column of a table. 

It takes a single argument, which is the name of the column or expression that you want to sum.

Here's an example query that uses the SUM() function: 

SELECT SUM(price) AS TotalPrice FROM Stores;

The resulting sum is assigned an alias "TotalPrice" using the AS keyword. The query returns a single row with a single column "TotalPrice" which contains the sum of all values in the "price" column of the "Stores" table. 

Initial situation in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

SUM function example:


mysql> SELECT SUM(available) AS InALLStores FROm Stores;
+-------------+
| InALLStores |
+-------------+
|        2633 |
+-------------+
1 row in set (0.00 sec)

mysql>

This MySQL query uses the SUM() function to calculate the total sum of the "available" column in the "Stores" table. 

The result of the SUM() function is assigned an alias "InALLStores" using the AS keyword.

The value returned in this case is 2633, which means that the total sum of all values in the "available" column of the "Stores" table is 2633. 

We can combine SUM and WHERE functions:


mysql> SELECT SUM(available) AS AllGoldPSUs FROM Stores WHERE product='GOLD PSU';
+-------------+
| AllGoldPSUs |
+-------------+
|         228 |
+-------------+
1 row in set (0.00 sec)

mysql>

Our query returns a single row with a single column "AllGoldPSUs" which contains the total sum of all values in the "available" column of the "Stores" table where the "product" column equals 'GOLD PSU'. 

Combination of SUM, WHERE and LIKE functions:


mysql> SELECT SUM(available) AS AllPSUs FROM Stores WHERE product LIKE "%PSU%";
+---------+
| AllPSUs |
+---------+
|     278 |
+---------+
1 row in set (0.00 sec)

mysql>

Here we use the SUM() function with a WHERE clause to calculate the total sum of the "available" column in the "Stores" table where the "product" column contains the string 'PSU'. 

The % symbol is a wildcard character used to match any sequence of characters, so the LIKE "%PSU%" condition matches any value in the "product" column that contains the string "PSU".

The result of the SUM() function is assigned an alias "AllPSUs" using the AS keyword.

MySQL MAX, MIN Functions

In MySQL, the MAX and MIN functions are used to return the maximum and minimum values, respectively, from a column or expression in a table. Here's how these functions work:

MAX function: The MAX function returns the maximum value from a column or expression. 

SELECT MAX(price) AS max_price FROM Stores;

Query will return a single row with a single column "max_price" that contains the highest value found in the "price" column of the "Stores" table.

MIN function: The MIN function returns the minimum value from a column or expression. 

SELECT MIN(price) AS min_price FROM Stores;

This query will return a single row with a single column "min_price" that contains the lowest value found in the "price" column of the "Stores" table. 

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

MAX function example:


mysql> SELECT MAX(price) AS MostExpensive FROM Stores;
+---------------+
| MostExpensive |
+---------------+
|           120 |
+---------------+
1 row in set (0.00 sec)

mysql>

Our query selects the maximum value of the "price" column in the "Stores" table and assigns it an alias "MostExpensive". The MAX function is used to calculate the maximum value of the "price" column.

The result is a single row with a single column "MostExpensive" which contains the highest value found in the "price" column of the "Stores" table. The value returned in this case is 120, which means that the highest value found in the "price" column of the "Stores" table is 120. 

MIN function example:


mysql> SELECT MIN(price) AS CheapestOne FROM Stores;
+-------------+
| CheapestOne |
+-------------+
|           5 |
+-------------+
1 row in set (0.00 sec)

mysql>

Here we selects the minimum value of the "price" column in the "Stores" table and assigns it an alias "CheapestOne". The MIN function is used to calculate the minimum value of the "price" column.

MAX and WHERE combination:


mysql> SELECT MAX(price) AS ExpensivePSU FROM Stores WHERE product='Gold PSU';
+--------------+
| ExpensivePSU |
+--------------+
|          100 |
+--------------+
1 row in set (0.00 sec)

mysql>

The result is a single row with a single column "ExpensivePSU" which contains the highest value found in the "price" column of the "Stores" table where the "product" column is "Gold PSU". 

The value returned in this case is 100, which means that the highest value found in the "price" column of the "Stores" table where the "product" column is "Gold PSU" is 100. 

Also, we can search for a substring:


mysql> SELECT MAX(price) AS MaxPriceCables FROM Stores WHERE product LIKE "%Cable%";
+----------------+
| MaxPriceCables |
+----------------+
|             25 |
+----------------+
1 row in set (0.00 sec)

mysql>

This MySQL query selects the maximum value of the "price" column in the "Stores" table where the "product" column contains the word "Cable". 

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...