Tuesday 10 July 2018

Mysql RLIKE operator

Mysql RLIKE operator

MySQL RLIKE operator performs a pattern match of a string expression against a pattern. The pattern is supplied as an argument.
Syntax:
RLIKE pat
Argument
NameDescription
patA pattern which is to be matched against an expression.
The operator is the synonym for REGEXP.
Example: MySQL RLIKE operator
The following MySQL statement will find the author’s name beginning with ‘w’. The ‘^’ have been used to match the beginning of the name.
Code:
SELECT * 
FROM author 
WHERE aut_name RLIKE '^w';


Sample table: author

Sample Output:
mysql> SELECT * FROM author 
    -> WHERE aut_name RLIKE '^w';
+--------+-----------------+---------+-----------+
| aut_id | aut_name        | country | home_city |
+--------+-----------------+---------+-----------+
| AUT001 | William Norton  | UK      | Cambridge | 
| AUT002 | William Maugham | Canada  | Toronto   | 
| AUT003 | William Anthony | UK      | Leeds     | 
+--------+-----------------+---------+-----------+
3 rows in set (0.00 sec)
PHP script
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>example-rlike-function - php mysql examples | w3resource</title>
<meta name="description" content="example-rlike-function - php mysql examples | w3resource"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>A list of Authors with their id, name country and home city. The list set against a condition, and that is, Author's name should not begin with 'w':</h2>
<table class='table table-bordered'>
<tr>
<th>Author's id</th><th>Author's name</th><th>Country</th><th>Home city</th>
</tr>
<?php
$hostname="your_hostname";
$username="your_username";
$password="your_password";
$db = "your_dbname";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT * 
FROM author 
WHERE aut_name RLIKE "^w"') as $row) {
echo "<tr>";
echo "<td>" . $row['aut_id'] . "</td>";
echo "<td>" . $row['aut_name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['home_city'] . "</td>";
echo "</tr>"; 
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

Copy

0 comments:

Post a Comment