MySQL | Data Types | Conditions | Queries | Relationships | Scripts
SQL can be coded in PHP scripts to access the MySQL server. Queries are coded in PHP functions(). phpMyAdmin is an open-source program with a GUI (graphical user interface) available as an option for managing databases with PHP. Check with a hosting server for instructions on initial database setup. A localhost, username, and password are needed to access MySQL from PHP.
MySQL must be connected and a database must be selected every time the database is accessed. mysql_connect() is a function() that connects to MySQL declaring the host, username, and password. die() is a function() that evaluates if MySQL does not connect. die() and echo are optional, used for testing and debugging. OR is a logical operator in PHP, as in MySQL...
If connected, the output is...
MySQL connected!
mysql_select_db() is a function() that selects the database...
If selected, the output is...
Database selected!
mysql_query() is a function() that sends queries to the database. This query creates a table with columns...
If created, the output is...
Table Created!
This query inserts data into specified columns in the table...
If selected, the output is...
Data inserted!
Connecting to MySQL, selecting a database, and query statements can all be coded within the same script...
Functions() and queries can be stored in PHP variables for easier access and storage.
This PHP script selects a database named business and creates a table named employee ...
The employee table is created with id, name, and age as columns. The id column is declared as the PRIMARY KEY. The output is...
Table Created!
INSERT INTO inserts data into a table. VALUES declares the data inserted into the columns...
Data is inserted into the name and age columns. The output is...
Data inserted!
This query calls up name and age from the employee table. while() generates each row. mysql_fetch_array() returns the row as an array...
The output is...
Person1 30
Person2 24
Person3 18
Data is selected with SELECT. The variable $result stores the result of mysql_query(). The % is an operator that tells MySQL to include all columns in the row. mysql_fetch_array() returns the first array of the result. The columns are name and age. $row['name'] accesses name, and $row['age'] accesses age...
The output is...
Name: Person1
Age: 30