MariaDB – Like Clause ”; Previous Next The WHERE clause provides a way to retrieve data when an operation uses an exact match. In situations requiring multiple results with shared characteristics, the LIKE clause accommodates broad pattern matching. A LIKE clause tests for a pattern match, returning a true or false. The patterns used for comparison accept the following wildcard characters: “%”, which matches numbers of characters (0 or more); and “_”, which matches a single character. The “_” wildcard character only matches characters within its set, meaning it will ignore latin characters when using another set. The matches are case-insensitive by default requiring additional settings for case sensitivity. A NOT LIKE clause allows for testing the opposite condition, much like the not operator. If the statement expression or pattern evaluate to NULL, the result is NULL. Review the general LIKE clause syntax given below − SELECT field, field2,… FROM table_name, table_name2,… WHERE field LIKE condition Employ a LIKE clause either at the command prompt or within a PHP script. The Command Prompt At the command prompt, simply use a standard command − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from products_tbl WHERE product_manufacturer LIKE ”XYZ%”; +————-+—————-+———————-+ | ID_number | Nomenclature | product_manufacturer | +————-+—————-+———————-+ | 12345 | Orbitron 4000 | XYZ Corp | +————-+—————-+———————-+ | 12346 | Orbitron 3000 | XYZ Corp | +————-+—————-+———————-+ | 12347 | Orbitron 1000 | XYZ Corp | +————-+—————-+———————-+ PHP Script Using Like Clause Use the mysql_query() function in statements employing the LIKE clause <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } $sql = ”SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl WHERE product_manufacturer LIKE “xyz%””; mysql_select_db(”PRODUCTS”); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not get data: ” . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo “Product ID:{$row[”product_id”]} <br> “. “Name: {$row[”product_name”]} <br> “. “Manufacturer: {$row[”product_manufacturer”]} <br> “. “Ship Date: {$row[”ship_date”]} <br> “. “——————————–<br>”; } echo “Fetched data successfullyn”; mysql_close($conn); ?> On successful data retrieval, you will see the following output − Product ID: 12345 Nomenclature: Orbitron 4000 Manufacturer: XYZ Corp Ship Date: 01/01/17 ———————————————- Product ID: 12346 Nomenclature: Orbitron 3000 Manufacturer: XYZ Corp Ship Date: 01/02/17 ———————————————- Product ID: 12347 Nomenclature: Orbitron 1000 Manufacturer: XYZ Corp Ship Date: 01/02/17 ———————————————- mysql> Fetched data successfully Print Page Previous Next Advertisements ”;
Category: mariadb
MariaDB – Update Query
MariaDB – Update Query ”; Previous Next The UPDATE command modifies existing fields by changing values. It uses the SET clause to specify columns for modification, and to specify the new values assigned. These values can be either an expression or the default value of the field. Setting a default value requires using the DEFAULT keyword. The command can also employ a WHERE clause to specify conditions for an update and/or an ORDER BY clause to update in a certain order. Review the following general syntax − UPDATE table_name SET field=new_value, field2=new_value2,… [WHERE …] Execute an UPDATE command from either the command prompt or using a PHP script. The Command Prompt At the command prompt, simply use a standard commandroot − root@host# mysql -u root -p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> UPDATE products_tbl SET nomenclature = ”Fiber Blaster 300Z” WHERE ID_number = 112; mysql> SELECT * from products_tbl WHERE ID_number=”112”; +————-+———————+———————-+ | ID_number | Nomenclature | product_manufacturer | +————-+———————+———————-+ | 112 | Fiber Blaster 300Z | XYZ Corp | +————-+———————+———————-+ PHP Update Query Script Employ the mysql_query() function in UPDATE command statements − <?php $dbhost = ‘localhost:3036’; $dbuser = ‘root’; $dbpass = ‘rootpassword’; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(‘Could not connect: ‘ . mysql_error()); } $sql = ‘UPDATE products_tbl SET product_name = ”Fiber Blaster 300z” WHERE product_id = 112’; mysql_select_db(‘PRODUCTS’); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(‘Could not update data: ‘ . mysql_error()); } echo “Updated data successfullyn”; mysql_close($conn); ?> On successful data update, you will see the following output − mysql> Updated data successfully Print Page Previous Next Advertisements ”;
MariaDB – Delete Query
MariaDB – Delete Query ”; Previous Next The DELETE command deletes table rows from the specified table, and returns the quantity deleted. Access the quantity deleted with the ROW_COUNT() function. A WHERE clause specifies rows, and in its absence, all rows are deleted. A LIMIT clause controls the number of rows deleted. In a DELETE statement for multiple rows, it deletes only those rows satisfying a condition; and LIMIT and WHERE clauses are not permitted. DELETE statements allow deleting rows from tables in different databases, but do not allow deleting from a table and then selecting from the same table within a subquery. Review the following DELETE syntax − DELETE FROM table_name [WHERE …] Execute a DELETE command from either the command prompt or using a PHP script. The Command Prompt At the command prompt, simply use a standard command − root@host# mysql –u root –p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> DELETE FROM products_tbl WHERE product_id=133; mysql> SELECT * from products_tbl WHERE ID_number=”133”; ERROR 1032 (HY000): Can”t find record in ”products_tbl” PHP Delete Query Script Use the mysql_query() function in DELETE command statements − <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } $sql = ”DELETE FROM products_tbl WHERE product_id = 261”; mysql_select_db(”PRODUCTS”); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not delete data: ” . mysql_error()); } echo “Deleted data successfullyn”; mysql_close($conn); ?> On successful data deletion, you will see the following output − mysql> Deleted data successfully mysql> SELECT * from products_tbl WHERE ID_number=”261”; ERROR 1032 (HY000): Can”t find record in ”products_tbl” Print Page Previous Next Advertisements ”;
MariaDB – Drop Tables
MariaDB – Drop Tables ”; Previous Next In this chapter, we will learn to delete tables. Table deletion is very easy, but remember all deleted tables are irrecoverable. The general syntax for table deletion is as follows − DROP TABLE table_name ; Two options exist for performing a table drop: use the command prompt or a PHP script. The Command Prompt At the command prompt, simply use the DROP TABLE SQL command − root@host# mysql -u root -p Enter password:******* mysql> use PRODUCTS; Database changed mysql> DROP TABLE products_tbl mysql> SELECT * from products_tbl ERROR 1146 (42S02): Table ”products_tbl” doesn”t exist PHP Drop Table Script PHP provides mysql_query() for dropping tables. Simply pass its second argument the appropriate SQL command − <html> <head> <title>Create a MariaDB Table</title> </head> <body> <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } echo ”Connected successfully<br />”; $sql = “DROP TABLE products_tbl”; mysql_select_db( ”PRODUCTS” ); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not delete table: ” . mysql_error()); } echo “Table deleted successfullyn”; mysql_close($conn); ?> </body> </html> On successful table deletion, you will see the following output − mysql> Table deleted successfully Print Page Previous Next Advertisements ”;
MariaDB – Select Query
MariaDB – Select Query ”; Previous Next In this chapter, we will learn how to select data from a table. SELECT statements retrieve selected rows. They can include UNION statements, an ordering clause, a LIMIT clause, a WHERE clause, a GROUP BY…HAVING clause, and subqueries. Review the following general syntax − SELECT field, field2,… FROM table_name, table_name2,… WHERE… A SELECT statement provides multiple options for specifying the table used − database_name.table_name table_name.column_name database_name.table_name.column_name All select statements must contain one or more select expressions. Select expressions consist of one of the following options − A column name. An expression employing operators and functions. The specification “table_name.*” to select all columns within the given table. The character “*” to select all columns from all tables specified in the FROM clause. The command prompt or a PHP script can be employed in executing a select statement. The Command Prompt At the command prompt, execute statements as follows − root@host# mysql -u root -p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> SELECT * from products_tbl +————-+—————+ | ID_number | Nomenclature | +————-+—————+ | 12345 | Orbitron 4000 | +————-+—————+ PHP Select Script Employ the same SELECT statement(s) within a PHP function to perform the operation. You will use the mysql_query() function once again. Review an example given below − <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } $sql = ”SELECT product_id, product_name,product_manufacturer, ship_date FROM products_tbl”; mysql_select_db(”PRODUCTS”); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not get data: ” . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo “Product ID :{$row[”product_id”]} <br> “. “Name: {$row[”product_name”]} <br> “. “Manufacturer: {$row[”product_manufacturer”]} <br> “. “Ship Date : {$row[”ship_date”]} <br>”. “——————————–<br>”; } echo “Fetched data successfullyn”; mysql_close($conn); ?> On successful data retrieval, you will see the following output − Product ID: 12345 Nomenclature: Orbitron 4000 Manufacturer: XYZ Corp Ship Date: 01/01/17 ———————————————- Product ID: 12346 Nomenclature: Orbitron 3000 Manufacturer: XYZ Corp Ship Date: 01/02/17 ———————————————- mysql> Fetched data successfully Best practices suggest releasing cursor memory after every SELECT statement. PHP provides the mysql_free_result() function for this purpose. Review its use as shown below − <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } $sql = ”SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl”; mysql_select_db(”PRODUCTS”); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not get data: ” . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_NUM)) { echo “Product ID :{$row[0]} <br> “. “Name: {$row[1]} <br> “. “Manufacturer: {$row[2]} <br> “. “Ship Date : {$row[3]} <br> “. “——————————–<br>”; } mysql_free_result($retval); echo “Fetched data successfullyn”; mysql_close($conn); ?> Print Page Previous Next Advertisements ”;
MariaDB – Data Types
MariaDB – Data Types ”; Previous Next Good field definitions are essential for the optimization of your database. The ideal approach requires that you exclusively use a field of the type and size needed. For example, if you will only use a field, five-characters wide, do not define a field, 20-characters wide. Field (or column) types are also known as data types given the data types stored within the field. MariaDB data types can be categorized as numeric, date and time, and string values. Numeric Data Types The numeric data types supported by MariaDB are as follows − TINYINT − This data type represents small integers falling within the signed range of -128 to 127, and the unsigned range of 0 to 255. BOOLEAN − This data type associates a value 0 with “false,” and a value 1 with “true.” SMALLINT − This data type represents integers within the signed range of -32768 to 32768, and the unsigned range of 0 to 65535. MEDIUMINT − This data type represents integers in the signed range of -8388608 to 8388607, and the unsigned range of 0 to 16777215. INT(also INTEGER) − This data type represents an integer of normal size. When marked as unsigned, the range spans 0 to 4294967295. When signed (the default setting), the range spans -2147483648 to 2147483647. When a column is set to ZEROFILL( an unsigned state), all its values are prepended by zeros to place M digits in the INT value. BIGINT − This data type represents integers within the signed range of 9223372036854775808 to 9223372036854775807, and the unsigned range of 0 to 18446744073709551615. DECIMAL( also DEC, NUMERIC, FIXED)− This data type represents precise fixed-point numbers, with M specifying its digits and D specifying the digits after the decimal. The M value does not add “-” or the decimal point. If D is set to 0, no decimal or fraction part appears and the value will be rounded to the nearest DECIMAL on INSERT. The maximum permitted digits is 65, and the maximum for decimals is 30. Default value for M on omission is 10, and 0 for D on omission. FLOAT − This data type represents a small, floating-point number of the value 0 or a number within the following ranges − -3.402823466E+38 to -1.175494351E-38 1.175494351E-38 to 3.402823466E+38 DOUBLE (also REAL and DOUBLE PRECISION) − This data type represents normal-size, floating-point numbers of the value 0 or within the following ranges − -1.7976931348623157E+308 to -2.2250738585072014E-308 2.2250738585072014E-308 to 1.7976931348623157E+308 BIT − This data type represents bit fields with M specifying the number of bits per value. On omission of M, the default is 1. Bit values can be applied with “ b’[value]’” in which value represents bit value in 0s and 1s. Zero-padding occurs automatically from the left for full length; for example, “10” becomes “0010.” Date and Time Data Types The date and time data types supported by MariaDB are as follows − DATE − This data type represents a date range of “1000-01-01” to “9999-12-31,” and uses the “YYYY-MM-DD” date format. TIME − This data type represents a time range of “-838:59:59.999999” to “838:59:59.999999.” DATETIME − This data type represents the range “1000-01-01 00:00:00.000000” to “9999-12-31 23:59:59.999999.” It uses the “YYYY-MM-DD HH:MM:SS” format. TIMESTAMP − This data type represents a timestamp of the “YYYY-MM-DD HH:MM:DD” format. It mainly finds use in detailing the time of database modifications, e.g., insertion or update. YEAR − This data type represents a year in 4-digit format. The four-digit format allows values in the range of 1901 to 2155, and 0000. String DataTypes The string type values supported by MariaDB are as follows − String literals − This data type represents character sequences enclosed by quotes. CHAR − This data type represents a right-padded, fixed-length string containing spaces of specified length. M represents column length of characters in a range of 0 to 255, its default value is 1. VARCHAR − This data type represents a variable-length string, with an M range (maximum column length) of 0 to 65535. BINARY − This data type represents binary byte strings, with M as the column length in bytes. VARBINARY − This data type represents binary byte strings of variable length, with M as column length. TINYBLOB − This data type represents a blob column with a maximum length of 255 (28 – 1) bytes. In storage, each uses a one-byte length prefix indicating the byte quantity in the value. BLOB − This data type represents a blob column with a maximum length of 65,535 (216 – 1) bytes. In storage, each uses a two-byte length prefix indicating the byte quantity in the value. MEDIUMBLOB − This data type represents a blob column with a maximum length of 16,777,215 (224 – 1) bytes. In storage, each uses a three-byte length prefix indicating the byte quantity in the value. LONGBLOB − This data type represents a blob column with a maximum length of 4,294,967,295(232 – 1) bytes. In storage, each uses a four-byte length prefix indicating the byte quantity in the value. TINYTEXT − This data type represents a text column with a maximum length of 255 (28 – 1) characters. In storage, each uses a one-byte length prefix indicating the byte quantity in the value. TEXT − This data type represents a text column with a maximum length of 65,535 (216 – 1) characters. In storage, each uses a two-byte length prefix indicating the byte quantity in the value. MEDIUMTEXT − This data type represents a text column with a maximum length of 16,777,215 (224 – 1) characters. In storage, each uses a three-byte length prefix indicating the byte quantity in the value. LONGTEXT − This data type represents a text column with a maximum length of 4,294,967,295 or 4GB (232 – 1) characters. In storage, each uses a four-byte length prefix indicating the byte quantity in the value. ENUM − This data type represents a string object having only a single value from a list. SET − This
MariaDB – Administration
MariaDB – Administration ”; Previous Next Before attempting to run MariaDB, first determine its current state, running or shutdown. There are three options for starting and stopping MariaDB − Run mysqld (the MariaDB binary). Run the mysqld_safe startup script. Run the mysql.server startup script. If you installed MariaDB in a non-standard location, you may have to edit location information in the script files. Stop MariaDB by simply adding a “stop” parameter with the script. If you would like to start it automatically under Linux, add startup scripts to your init system. Each distribution has a different procedure. Refer to your system documentation. Creating a User Account Create a new user account with the following code − CREATE USER ”newusername”@”localhost” IDENTIFIED BY ”userpassword”; This code adds a row to the user table with no privileges. You also have the option to use a hash value for the password. Grant the user privileges with the following code − GRANT SELECT, INSERT, UPDATE, DELETE ON database1 TO ”newusername”@”localhost”; Other privileges include just about every command or operation possible in MariaDB. After creating a user, execute a “FLUSH PRIVILEGES” command in order to refresh grant tables. This allows the user account to be used. The Configuration File After a build on Unix/Linux, the configuration file “/etc/mysql/my.cnf” should be edited to appear as follow − # Example mysql config file. # You can copy this to one of: # /etc/my.cnf to set global options, # /mysql-data-dir/my.cnf to get server specific options or # ~/my.cnf for user specific options. # # One can use all long options that the program supports. # Run the program with –help to get a list of available options # This will be passed to all mysql clients [client] #password = my_password #port = 3306 #socket = /tmp/mysql.sock # Here is entries for some specific programs # The following values assume you have at least 32M ram # The MySQL server [mysqld] #port = 3306 #socket = /tmp/mysql.sock temp-pool # The following three entries caused mysqld 10.0.1-MariaDB (and possibly other versions) to abort… # skip-locking # set-variable = key_buffer = 16M # set-variable = thread_cache = 4 loose-innodb_data_file_path = ibdata1:1000M loose-mutex-deadlock-detector gdb ######### Fix the two following paths # Where you want to have your database data = /path/to/data/dir # Where you have your mysql/MariaDB source + sql/share/english language = /path/to/src/dir/sql/share/english [mysqldump] quick MariaDB 8 set-variable = max_allowed_packet=16M [mysql] no-auto-rehash [myisamchk] set-variable = key_buffer = 128M Edit the lines “data= ” and “language= ” to match your environment. After file modification, navigate to the source directory and execute the following − ./scripts/mysql_install_db –srcdir = $PWD –datadir = /path/to/data/dir — user = $LOGNAME Omit the “$PWD” variable if you added datadir to the configuration file. Ensure “$LOGNAME” is used when running version 10.0.1 of MariaDB. Administration Commands Review the following list of important commands you will regularly use when working with MariaDB − USE [database name] − Sets the current default database. SHOW DATABASES − Lists the databases currently on the server. SHOW TABLES − Lists all non-temporary tables. SHOW COLUMNS FROM [table name] − Provides column information pertaining to the specified table. SHOW INDEX FROM TABLENAME [table name] − Provides table index information relating to the specified table. SHOW TABLE STATUS LIKE [table name]G – − Provides tables with information about non-temporary tables, and the pattern that appears after the LIKE clause is used to fetch table names. Print Page Previous Next Advertisements ”;
MariaDB – Introduction
MariaDB – Introduction ”; Previous Next A database application exists separate from the main application and stores data collections. Every database employs one or multiple APIs for the creation, access, management, search, and replication of the data it contains. Databases also use non-relational data sources such as objects or files. However, databases prove the best option for large datasets, which would suffer from slow retrieval and writing with other data sources. Relational database management systems, or RDBMS, store data in various tables.Relationships between these tables are established using primary keys and foreign keys. RDBMS offers the following features − They enable you to implement a data source with tables, columns, and indices. They ensure the integrity of references across rows of multiple tables. They automatically update indices. They interpret SQL queries and operations in manipulating or sourcing data from tables. RDBMS Terminology Before we begin our discussion of MariaDB, let us review a few terms related to databases. Database − A database is a data source consisting of tables holding related data. Table − A table, meaning a spreadsheet, is a matrix containing data. Column − A column, meaning data element, is a structure holding data of one type; for example, shipping dates. Row − A row is a structure grouping related data; for example, data for a customer. It is also known as a tuple, entry, or record. Redundancy − This term refers to storing data twice in order to accelerate the system. Primary Key − This refers to a unique, identifying value. This value cannot appear twice within a table, and there is only one row associated with it. Foreign Key − A foreign key serves as a link between two tables. Compound Key − A compound key, or composite key, is a key that refers to multiple columns. It refers to multiple columns due to a column lacking a unique quality. Index − An index is virtually identical to the index of a book. Referential Integrity − This term refers to ensuring all foreign key values point to existing rows. MariaDB Database MariaDB is a popular fork of MySQL created by MySQL”s original developers. It grew out of concerns related to MySQL”s acquisition by Oracle. It offers support for both small data processing tasks and enterprise needs. It aims to be a drop-in replacement for MySQL requiring only a simple uninstall of MySQL and an install of MariaDB. MariaDB offers the same features of MySQL and much more. Key Features of MariaDB The important features of MariaDB are − All of MariaDB is under GPL, LGPL, or BSD. MariaDB includes a wide selection of storage engines, including high-performance storage engines, for working with other RDBMS data sources. MariaDB uses a standard and popular querying language. MariaDB runs on a number of operating systems and supports a wide variety of programming languages. MariaDB offers support for PHP, one of the most popular web development languages. MariaDB offers Galera cluster technology. MariaDB also offers many operations and commands unavailable in MySQL, and eliminates/replaces features impacting performance negatively. Getting Started Before you begin this tutorial, make sure you have some basic knowledge of PHP and HTML, specifically material discussed in our PHP and HTML tutorials. This guide focuses on use of MariaDB in a PHP environment, so our examples will be most useful for PHP developers. We strongly recommend reviewing our PHP Tutorial if you lack familiarity or need to review. Print Page Previous Next Advertisements ”;
MariaDB – Connection
MariaDB – Connection ”; Previous Next One way to establish a connection with MariaDB consists of using the mysql binary at the command prompt. MYSQL Binary Review an example given below. [root@host]# mysql -u root -p Enter password:****** The code given above connects to MariaDB and provides a command prompt for executing SQL commands. After entering the code, a welcome message should appear indicating a successful connection, with the version number displayed. Welcome to the MariaDB monitor. Commands end with ; or g. Your MariaDB connection id is 122323232 Server version: 5.5.40-MariaDB-log Type ”help;” or ”h” for help. Type ”c” to clear the current input statement. mysql> The example uses root access, but any user with privileges can of course access the MariaDB prompt and perform operations. Disconnect from MariaDB through the exit command as follows − mysql> exit PHP Connection Script Another way to connect to and disconnect from MariaDB consists of employing a PHP script. PHP provides the mysql_connect() function for opening a database connection. It uses five optional parameters, and returns a MariaDB link identifier after a successful connection, or a false on unsuccessful connection. It also provides the mysql_close() function for closing database connections, which uses a single parameter. Syntax Review the following PHP connection script syntax − connection mysql_connect(server,user,passwd,new_link,client_flag); The description of the parameters is given below − Sr.No Parameter & Description 1 server This optional parameter specifies the host name running the database server. Its default value is “localhost:.3036.” 2 user This optional parameter specifies the username accessing the database. Its default value is the owner of the server. 3 passwd This optional parameter specifies the user”s password. Its default value is blank. 4 new_link This optional parameter specifies that on a second call to mysql_connect() with identical arguments, rather than a new connection, the identifier of the current connection will be returned. 5 client flags This optional parameter uses a combination of the following constant values − MYSQL_CLIENT_SSL − It uses ssl encryption. MYSQL_CLIENT_COMPRESS − It uses compression protocol. MYSQL_CLIENT_IGNORE_SPACE − It permits space after function names. MYSQL_CLIENT_INTERACTIVE − It permits interactive timeout seconds of inactivity prior to closing the connection. Review the PHP disconnection script syntax given below − bool mysql_close ( resource $link_identifier ); If you omit the resource, the most recent opened resource will close. It returns a value of true on a successful close, or false. Try the following example code to connect with a MariaDB server − <html> <head> <title>Connect to MariaDB Server</title> </head> <body> <?php $dbhost = ”localhost:3036”; $dbuser = ”guest1”; $dbpass = ”guest1a”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } echo ”Connected successfully”; mysql_close($conn); ?> </body> </html> On successful connection, you will see the following output − mysql> Connected successfully Print Page Previous Next Advertisements ”;
MariaDB – Create Database
MariaDB – Create Database ”; Previous Next Creation or deletion of databases in MariaDB requires privileges typically only given to root users or admins. Under these accounts, you have two options for creating a database − the mysqladmin binary and a PHP script. mysqladmin binary The following example demonstrates the use of the mysqladmin binary in creating a database with the name Products − [root@host]# mysqladmin -u root -p create PRODUCTS Enter password:****** PHP Create Database Script PHP employs the mysql_query function in creating a MariaDB database. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not. Syntax Review the following create database script syntax − bool mysql_query( sql, connection ); The description of the parameters is given below − S.No Parameter & Description 1 sql This required parameter consists of the SQL query needed to perform the operation. 2 connection When not specified, this optional parameter uses the most recent connection used. Try the following example code for creating a database − <html> <head> <title>Create a MariaDB Database</title> </head> <body> <?php $dbhost = ”localhost:3036”; $dbuser = ”root”; $dbpass = ”rootpassword”; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(”Could not connect: ” . mysql_error()); } echo ”Connected successfully<br />”; $sql = ”CREATE DATABASE PRODUCTS”; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(”Could not create database: ” . mysql_error()); } echo “Database PRODUCTS created successfullyn”; mysql_close($conn); ?> </body> </html> On successful deletion, you will see the following output − mysql> Database PRODUCTS created successfully mysql> SHOW DATABASES; +———————–+ | Database | +———————–+ | PRODUCTS | +———————–+ Print Page Previous Next Advertisements ”;