MySQLi – Useful Functions

MySQLi – Useful Functions ”; Previous Next Here is the list of all important MySQLi functions. Each function has been explained along with suitable example. mysqli::$affected_rows − It used to get the information about number of affected rows in a previous MySQL operation mysqli::autocommit − It used to turn on or off auto-committing database modifications operation mysqli::begin_transaction − It used to start a transaction mysqli::change_user − It used to change the user of the specified database connection mysqli::character_set_name – It returns the default character set for the database connection. mysqli::$client_info − It is used to get MySQL client info. mysqli::$client_version − It returns the MySQL client version as a string. mysqli::close − It closes a previously opened database connection. mysqli::commit − It commits the current transaction. mysqli::$connect_errno − It returns the error code from last connect call. mysqli::connect_error − It returns a string description of the last connect error. mysqli::__construct − It used to open a new connection to the MySQL server mysqli::debug − It used to performs debugging operations mysqli::dump_debug_info − It is used to dump debugging information into the log mysqli::$errno − It returns the error code for the most recent function call mysqli::$error_list − It returns a list of errors from the last command executed mysqli::$error − It returns a string description of the last error mysqli::$field_count − It returns the number of columns for the most recent query mysqli::get_charset − It returns a character set object mysqli::get_client_info − It is used to get MySQL client info mysqli::mysqli_get_client_stats − It returns client per-process statistics mysqli::mysqli_get_client_version − It returns the MySQL client version as an integer mysqli::get_connection_stats − It returns statistics about the client connection mysqli::$host_info − It returns a string representing the type of connection used mysqli::$protocol_version − It returns the version of the MySQL protocol used mysqli::$server_info − It returns the version of the MySQL server mysqli::$server_version − It returns the version of the MySQL server as an integer mysqli::get_warnings − It is used to get result of SHOW WARNINGS mysqli::$info − It retrieves information about the most recently executed query mysqli::$insert_id − It returns the auto generated id used in the latest query mysqli::kill − It asks the server to kill a MySQL thread mysqli::more_results − It used to check if there are any more query results from a multi query mysqli::multi_query − It performs a query on the database mysqli::next_result − It prepares next result from multi_query mysqli::options − It used to set options mysqli::ping − It is used to ping a server mysqli::poll − It used to poll connections mysqli::prepare − It used to prepare an SQL statement for execution. mysqli::query − It is used to perform a query on the database. mysqli::real_connect − It opens a connection to a mysql server. mysqli::real_escape_string − It escapes special characters in a string for use in an SQL statement mysqli::real_query − It is used to execute an SQL query. mysqli::real_async_query − It is used to get result from async query mysqli::refresh − It used to refresh an SQL statement for execution. mysqli::release_savepoint − It removes the named savepoint from the set of savepoints of the current transaction mysqli::rollback − It rolls back current transaction mysqli::rpl_query_type − It returns RPL query type mysqli::select_db − It is used to selects the default database for database queries mysqli::send_query − It is used to send the query and return mysqli::set_charset − It sets the default client character set mysqli::set_local_infile_default − It is used to unsets user defined handler for load local infile command mysqli::set_local_infile_handler − It is used to set callback function for LOAD DATA LOCAL INFILE command mysqli::$sqlstate − It returns the SQLSTATE error from previous MySQL operation. mysqli::ssl_set − It is used for establishing secure connections using SSL mysqli::stat − It is used to set callback function for LOAD DATA LOCAL INFILE command mysqli::stmt_init − It is used to initialize a statement and returns an object for use with mysqli_stmt_prepare. mysqli::mysqli::$thread_id − It returns the thread ID for the current connection mysqli::thread_safe − It returns whether thread safety is given or not. mysqli::use_result − It is used to initiate a result set retrieval mysqli::$warning_count − It returns the number of warnings from the last query for the given link Print Page Previous Next Advertisements ”;

MySQLi – Discussion

Discuss MySQLi ”; Previous Next The MySQLi extension was introduced with PHP version 5.0.0 and the MySQL Native Driver was included in PHP version 5.3.0. i stands for improved in MySQLi and provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database. You would require to call the MySQLi functions in the same way you call any other PHP function. Print Page Previous Next Advertisements ”;

MySQL – Using Sequences

MySQLi – Using Sequences ”; Previous Next A sequence is a set of integers 1, 2, 3, … that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value and sequences provide an easy way to generate them. This chapter describes how to use sequences in MySQL. Using AUTO_INCREMENT column The simplest way in MySQL to use Sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care. Example Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it”s auto incremented by MySQL. mysql>CREATE TABLE tutorials_auto( id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(30) NOT NULL,PRIMARY KEY(id)); Query OK, 0 rows affected (0.28 sec) mysql>INSERT INTO tutorials_auto(id,name) VALUES(NULL,”sai”),(NULL,”ram”); Query OK, 2 rows affected (0.12 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM insect ORDER BY id; +—-+——+ | id | name | +—-+——+ | 1 | sai | | 2 | ram | +—-+——+ 2 rows in set (0.05 sec) Obtain AUTO_INCREMENT Values LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve auto incremented value of last record. PERL Example Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle: $dbh→do (“INSERT INTO tutorials_auto (name,date,origin) VALUES(”moth”,”2001-09-14”,”windowsill”)”); my $seq = $dbh→{mysqli_insertid}; PHP Example After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ) − mysql_query (“INSERT INTO tutorials_auto (name,date,origin) VALUES(”moth”,”2001-09-14”,”windowsill”)”, $conn_id); $seq = mysqli_insert_id ($conn_id); Renumbering an Existing Sequence There may be a case when you have deleted many records from a table and you want to resequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having joins with other table. If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique − mysql> ALTER TABLE tutorials_auto DROP id; mysql> ALTER TABLE tutorials_auto → ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, → ADD PRIMARY KEY (id); Starting a Sequence at a Particular Value By default, MySQLi will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100. mysql> CREATE TABLE tutorials_auto → ( → id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100, → PRIMARY KEY (id), → name VARCHAR(30) NOT NULL, → ); Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE. mysql> ALTER TABLE tutorials_auto AUTO_INCREMENT = 100; Print Page Previous Next Advertisements ”;

MySQLi – Quick Guide

MySQLi – Quick Guide ”; Previous Next MySQLi – Introduction MySQLi is an extension to MySQL API available in PHP and is introduced from PHP 5.0 onwards. It is also known as MySQL improved extension. Motivation behind MySQLi was to take advantage of new features available in MySQL 4.1.3 onwards. It provides numerous benefits over MySQL extension. MySQL provides an object oriented interface. It provides both object oriented and procedural approach to handle database operations. Object Oriented Interface <?php $mysqli = mysqli_connect(“localhost”, “user”, “password”, “database-name”); $result = mysqli_query($mysqli, “SELECT ”Welcome to MySQLi” AS _msg FROM DUAL”); $row = mysqli_fetch_assoc($result); echo $row[”_msg”]; ?> Procedural Approach <?php $mysqli = new mysqli(“localhost”, “user”, “password”, “database-name”); $result = $mysqli→query(“SELECT ”Welcome to MySQLi” AS _msg FROM DUAL”); $row = $result→fetch_assoc(); echo $row[”_msg”]; ?> MySQLi supports prepared statments. MySQLi supports multiple statments. MySQLi supports transactions. MySQLi provides enhanced debugging capabilities. MySQLi – PHP Syntax MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities. This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL with PERL, then you can consider reading the PERL Tutorial. PHP provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database. You would require to call the PHP functions in the same way you call any other PHP function. The PHP functions for use with MySQL have the following general format − mysqli function(value,value,…); The second part of the function name is specific to the function, usually a word that describes what the function does. The following are two of the functions, which we will use in our tutorial − $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); mysqli→query(,”SQL statement”); The following example shows a generic syntax of PHP to call any MySQL function. <html> <head> <title>PHP with MySQL</title> </head> <body> <?php $retval = mysqli – > <i>function</i>(value, [value,…]); if( !$retval ) { die ( “Error: a related error message” ); } // Otherwise MySQL or PHP Statements ?> </body> </html> Starting from the next chapter, we will see all the important MySQL functionality along with PHP. MySQLi – Connection MySQL Connection Using MySQL Binary You can establish the MySQL database using the mysql binary at the command prompt. Example Here is a simple example to connect to the MySQL server from the command prompt − [root@host]# mysql -u root -p Enter password:****** This will give you the mysqli command prompt where you will be able to execute any SQL command. Following is the result of above command − The following code block shows the result of above code − Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 2854760 to server version: 5.0.9 Type ”help;” or ”h” for help. Type ”c” to clear the buffer. In the above example, we have used root as a user but you can use any other user as well. Any user will be able to perform all the SQL operations, which are allowed to that user. You can disconnect from the MySQL database any time using the exit command at mysql> prompt. mysql> exit Bye MySQL Connection Using PHP Script PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure. Syntax $mysqli = new mysqli($host, $username, $passwd, $dbName, $port, $socket); Sr.No. Parameter & Description 1 $host Optional − The host name running the database server. If not specified, then the default value will be localhost:3306. 2 $username Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process. 3 $passwd Optional − The password of the user accessing the database. If not specified, then the default will be an empty password. 4 $dbName Optional − database name on which query is to be performed. 5 $port Optional − the port number to attempt to connect to the MySQL server.. 6 $socket Optional − socket or named pipe that should be used. You can disconnect from the MySQL database anytime using another PHP function close(). Syntax $mysqli→close(); Example Try the following example to connect to a MySQL server − Copy and paste the following example as mysql_example.php − <html> <head> <title>Connecting MySQL Server</title> </head> <body> <?php $dbhost = ”localhost”; $dbuser = ”root”; $dbpass = ”root@123”; $mysqli = new mysqli($dbhost, $dbuser, $dbpass); if($mysqli→connect_errno ) { printf(“Connect failed: %s<br />”, $mysqli→connect_error); exit(); } printf(”Connected successfully.<br />”); $mysqli→close(); ?> </body> </html> Output Access the mysql_example.php deployed on apache web server and verify the output. Connected successfully. MySQLi – Create Database Create Database Using mysqladmin You would need special privileges to create or to delete a MySQL database. So assuming you have access to the root user, you can create any database using the mysql mysqladmin binary. Example Here is a simple example to create a database called TUTORIALS − [root@host]# mysqladmin -u root -p create TUTORIALS Enter password:****** This will create a MySQL database called TUTORIALS. Create a Database

MySQL – Handling Duplicates

MySQLi – Handling Duplicates ”; Previous Next Tables or result sets sometimes contain duplicate records. Sometimes, it is allowed but sometimes it is required to stop duplicate records. Sometimes, it is required to identify duplicate records and remove them from the table. This chapter will describe how to prevent duplicate records occurring in a table and how to remove already existing duplicate records. Preventing Duplicates from Occurring in a Table You can use a PRIMARY KEY or UNIQUE Index on a table with appropriate fields to stop duplicate records. Let”s take one example: The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name. CREATE TABLE person_tbl ( first_name CHAR(20), last_name CHAR(20), sex CHAR(10) ); To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it”s also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values − CREATE TABLE person_tbl ( first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, sex CHAR(10), PRIMARY KEY (last_name, first_name) ); The presence of a unique index in a table normally causes an error to occur if you insert a record into the table that duplicates an existing record in the column or columns that define the index. Use INSERT IGNORE rather than INSERT. If a record doesn”t duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error. Following example does not error out and same time it will not insert duplicate records. mysql> INSERT IGNORE INTO person_tbl (last_name, first_name) → VALUES( ”Jay”, ”Thomas”); Query OK, 1 row affected (0.00 sec) mysql> INSERT IGNORE INTO person_tbl (last_name, first_name) → VALUES( ”Jay”, ”Thomas”); Query OK, 0 rows affected (0.00 sec) Use REPLACE rather than INSERT. If the record is new, it”s inserted just as with INSERT. If it”s a duplicate, the new record replaces the old one − mysql> REPLACE INTO person_tbl (last_name, first_name) → VALUES( ”Ajay”, ”Kumar”); Query OK, 1 row affected (0.00 sec) mysql> REPLACE INTO person_tbl (last_name, first_name) → VALUES( ”Ajay”, ”Kumar”); Query OK, 2 rows affected (0.00 sec) INSERT IGNORE and REPLACE should be chosen according to the duplicate-handling behavior you want to effect. INSERT IGNORE keeps the first of a set of duplicated records and discards the rest. REPLACE keeps the last of a set of duplicates and erase out any earlier ones. Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table. CREATE TABLE person_tbl ( first_name CHAR(20) NOT NULL, last_name CHAR(20) NOT NULL, sex CHAR(10) UNIQUE (last_name, first_name) ); Counting and Identifying Duplicates Following is the query to count duplicate records with first_name and last_name in a table. mysql> SELECT COUNT(*) as repetitions, last_name, first_name → FROM person_tbl → GROUP BY last_name, first_name → HAVING repetitions > 1; This query will return a list of all the duplicate records in person_tbl table. In general, to identify sets of values that are duplicated, do the following − Determine which columns contain the values that may be duplicated. List those columns in the column selection list, along with COUNT(*). List the columns in the GROUP BY clause as well. Add a HAVING clause that eliminates unique values by requiring group counts to be greater than one. Eliminating Duplicates from a Query Result: You can use DISTINCT along with SELECT statement to find out unique records available in a table. mysql> SELECT DISTINCT last_name, first_name → FROM person_tbl → ORDER BY last_name; An alternative to DISTINCT is to add a GROUP BY clause that names the columns you”re selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns − mysql> SELECT last_name, first_name → FROM person_tbl → GROUP BY (last_name, first_name); Removing Duplicates Using Table Replacement If you have duplicate records in a table and you want to remove all the duplicate records from that table, then here is the procedure − mysql> CREATE TABLE tmp SELECT last_name, first_name, sex → FROM person_tbl; → GROUP BY (last_name, first_name); mysql> DROP TABLE person_tbl; mysql> ALTER TABLE tmp RENAME TO person_tbl; An easy way of removing duplicate records from a table is to add an INDEX or PRIMAY KEY to that table. Even if this table is already available, you can use this technique to remove duplicate records and you will be safe in future as well. mysql> ALTER IGNORE TABLE person_tbl → ADD PRIMARY KEY (last_name, first_name); Print Page Previous Next Advertisements ”;

MySQL – Clone Tables

MySQLi – Clone Tables ”; Previous Next There may be a situation when you need an exact copy of a table and CREATE TABLE … SELECT doesn”t suit your purposes because the copy must include the same indexes, default values, and so forth. You can handle this situation by following steps − Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table”s structure, indexes and all. Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have exact clone table. Optionally, if you need the table contents copied as well, issue an INSERT INTO … SELECT statement, too. Example Try out the following example to create a clone table for tutorials_inf. Step 1 Get complete structure about table. mysql> SHOW CREATE TABLE tutorials_inf G; *************************** 1. row *************************** Table: tutorials_inf Create Table: CREATE TABLE `tutorials_inf` ( `id` int(11) NOT NULL, `name` varchar(20) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `AUTHOR_INDEX` (`name`), UNIQUE KEY `NAME_INDEX` (`name`), KEY `id` (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = latin1 1 row in set (0.05 sec) ERROR: No query specified Step 2 Rename this table and create another table. mysql> CREATE TABLE tutorials_clone( → id int(11) NOT NULL, → name varchar(20) NOT NULL, → PRIMARY KEY (id), → UNIQUE KEY AUTHOR_INDEX (name), → UNIQUE KEY NAME_INDEX (name), → KEY id (id)); Query OK, 0 rows affected (1.80 sec) Step 3 After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO… SELECT statement. mysql> INSERT INTO tutorials_clone(id,name) SELECT id,name from tutorials_inf; Query OK, 4 rows affected (0.19 sec) Records: 4 Duplicates: 0 Warnings: 0 Finally, you will have exact clone table as you wanted to have. Print Page Previous Next Advertisements ”;

MySQLi – Useful Resources

MySQLi – Useful Resources ”; Previous Next The following resources contain additional information on MySQLi. Please use them to get more in-depth knowledge on this. Useful Links on MySQLi MySQLi site − Microsoft Official Site for MySQLi. MySQLi Wiki − Wikipedia Reference for MySQLi. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

MySQL – Alter Command

MySQLi – ALTER Command ”; Previous Next MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table. Let”s begin with creation of a table called tutorials_alter. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> create table tutorials_alter → ( → i INT, → c CHAR(1) → ); Query OK, 0 rows affected (0.27 sec) mysql> SHOW COLUMNS FROM tutorials_alter; +——-+———+——+—–+———+——-+ | Field | Type | Null | Key | Default | Extra | +——-+———+——+—–+———+——-+ | i | int(11) | YES | | NULL | | | c | char(1) | YES | | NULL | | +——-+———+——+—–+———+——-+ 2 rows in set (0.02 sec) Dropping, Adding or Repositioning a Column Suppose you want to drop an existing column i from above MySQL table then you will use DROP clause along with ALTER command as follows − mysql> ALTER TABLE tutorials_alter DROP i; A DROP will not work if the column is the only one left in the table. To add a column, use ADD and specify the column definition. The following statement restores the i column to tutorials_alter − mysql> ALTER TABLE tutorials_alter ADD i INT; After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have quite the same structure. That”s because new columns are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one. mysql> SHOW COLUMNS FROM tutorials_alter; +——-+———+——+—–+———+——-+ | Field | Type | Null | Key | Default | Extra | +——-+———+——+—–+———+——-+ | c | char(1) | YES | | NULL | | | i | int(11) | YES | | NULL | | +——-+———+——+—–+———+——-+ 2 rows in set (0.01 sec) To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column or AFTER col_name to indicate that the new column should be placed after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has − ALTER TABLE testalter_tbl DROP i; ALTER TABLE testalter_tbl ADD i INT FIRST; ALTER TABLE testalter_tbl DROP i; ALTER TABLE testalter_tbl ADD i INT AFTER c; The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position. Changing a Column Definition or Name To change a column”s definition, use MODIFY or CHANGE clause along with ALTER command. For example, to change column c from CHAR(1) to CHAR(10), do this − mysql> ALTER TABLE tutorials_alter MODIFY c CHAR(10); With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name. Try out the following example: mysql> ALTER TABLE tutorials_alter CHANGE i j BIGINT; If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement will be as expected − mysql> ALTER TABLE tutorials_alter CHANGE j j INT; The Effect of ALTER TABLE on Null and Default Value Attributes − When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values and what its default value is. In fact, if you don”t do this, MySQL automatically assigns values for these attributes. Here is the example, where NOT NULL column will have value 100 by default. mysql> ALTER TABLE tutorials_alter → MODIFY j BIGINT NOT NULL DEFAULT 100; If you don”t use above command, then MySQL will fill up NULL values in all the columns. Changing a Column”s Default Value You can change a default value for any column using ALTER command. Try out the following example. mysql> ALTER TABLE tutorials_alter ALTER j SET DEFAULT 1000; mysql> SHOW COLUMNS FROM tutorials_alter; +——-+————+——+—–+———+——-+ | Field | Type | Null | Key | Default | Extra | +——-+————+——+—–+———+——-+ | c | char(10) | YES | | NULL | | | j | bigint(20) | NO | | 1000 | | +——-+————+——+—–+———+——-+ 2 rows in set (0.02 sec) You can remove default constraint from any column by using DROP clause along with ALTER command. mysql> ALTER TABLE tutorials_alter ALTER j DROP DEFAULT; mysql> SHOW COLUMNS FROM tutorials_alter; +——-+————+——+—–+———+——-+ | Field | Type | Null | Key | Default | Extra | +——-+————+——+—–+———+——-+ | c | char(10) | YES | | NULL | | | j | bigint(20) | NO | | NULL | | +——-+————+——+—–+———+——-+ 2 rows in set (0.02 sec) Changing a Table Type You can use a table type by using TYPE clause along with ALTER command. To find out the current type of a table, use the SHOW TABLE STATUS statement. mysql> SHOW TABLE STATUS LIKE ”tutorials_alter”G *************************** 1. row *************************** Name: tutorials_alter Engine: InnoDB Version: 10 Row_format: Compact Rows: 0 Avg_row_length: 0 Data_length: 16384 Max_data_length: 0 Index_length: 0 Data_free: 0 Auto_increment: NULL Create_time: 2017-02-17 11:30:29 Update_time: NULL Check_time: NULL Collation: latin1_swedish_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec) Renaming a Table To rename a table, use the RENAME option of the ALTER TABLE statement. Try out the following example to rename tutorials_alter to tutorials_bks. mysql> ALTER TABLE tutorials_alter RENAME TO tutorials_bks; You can use ALTER command to create and drop INDEX on a MySQL file. We

MySQL – Regexps

MySQLi – Regexps ”; Previous Next You have seen MySQL pattern matching with LIKE …%. MySQL supports another type of pattern matching operation based on regular expressions and the REGEXP operator. If you are aware of PHP or PERL, then it”s very simple for you to understand because this matching is very similar to those scripting regular expressions. Following is the table of pattern, which can be used along with REGEXP operator. Pattern What the pattern matches ^ Beginning of string $ End of string . Any single character […] Any character listed between the square brackets [^…] Any character not listed between the square brackets p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3 * Zero or more instances of preceding element + One or more instances of preceding element {n} n instances of preceding element {m,n} m through n instances of preceding element Examples Now based on above table, you can device various type of SQL queries to meet your requirements. Here, I”m listing few for your understanding. Consider we have a table called tutorials_inf and it”s having a field called name − Query to find all the names starting with ”sa” mysql> SELECT * FROM tutorials_inf WHERE name REGEXP ”^sa”; The sample output should be like this − +—-+——+ | id | name | +—-+——+ | 1 | sai | +—-+——+ 1 row in set (0.00 sec) Query to find all the names ending with ”ai” mysql> SELECT * FROM tutorials_inf WHERE name REGEXP ”ai$”; The sample output should be like this − +—-+——+ | id | name | +—-+——+ | 1 | sai | +—-+——+ 1 row in set (0.00 sec) Query to find all the names, which contain ”a” mysql> SELECT * FROM tutorials_inf WHERE name REGEXP ”a”; The sample output should be like this − +—-+——-+ | id | name | +—-+——-+ | 1 | sai | | 3 | ram | | 4 | johar | +—-+——-+ 3 rows in set (0.00 sec) Query to find all the names starting with a vowel mysql> SELECT * FROM tutorials_inf WHERE name REGEXP ”^[aeiou]”; Print Page Previous Next Advertisements ”;

MySQL – Temporary Tables

MySQLi – Temporary Tables ”; Previous Next The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates. As stated earlier, temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table. Example Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysqli_query() function. mysql> CREATE TEMPORARY TABLE SalesSummary ( → product_name VARCHAR(50) NOT NULL → , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00 → , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00 → , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 → ); Query OK, 0 rows affected (0.00 sec) mysql> INSERT INTO SalesSummary → (product_name, total_sales, avg_unit_price, total_units_sold) → VALUES → (”cucumber”, 100.25, 90, 2); mysql> SELECT * FROM SalesSummary; +————–+————-+—————-+——————+ | product_name | total_sales | avg_unit_price | total_units_sold | +————–+————-+—————-+——————+ | cucumber | 100.25 | 90.00 | 2 | +————–+————-+—————-+——————+ 1 row in set (0.00 sec) When you issue a SHOW TABLES command, then your temporary table would not be listed out in the list. Now, if you will log out of the MySQL session and then you will issue a SELECT command, then you will find no data available in the database. Even your temporary table would also not exist. Dropping Temporary Tables By default, all the temporary tables are deleted by MySQL when your database connection gets terminated. Still if you want to delete them in between, then you do so by issuing DROP TABLE command. Following is the example on dropping a temporary table − mysql> DROP TABLE SalesSummary; mysql> SELECT * FROM SalesSummary; ERROR 1146: Table ”TUTORIALS.SalesSummary” doesn”t exist Print Page Previous Next Advertisements ”;