w3resource
MYSQL Tutorial

MySQL ENCODE() function

ENCODE() function

MySQL ENCODE() function encrypts a string. This function returns a binary string of the same length of the original string.

Syntax:

ENCODE(str, pass_str);

Arguments

Name Description
str A string which is to be encrypted.
pass_str A string to encrypt str.

Syntax Diagram:

MySQL ENCODE() Function - Syntax Diagram

MySQL Version: 5.6


Example:

Code:

SELECT ENCODE('mytext','mykeystring');

Explanation

The above MySQL statement will encrypt the string 'mytext' with 'mykeystring'.

Sample Output:

mysql> SELECT ENCODE('mytext','mykeystring');
+--------------------------------+
| ENCODE('mytext','mykeystring') |
+--------------------------------+
| ">¿¡È                         | 
+--------------------------------+
1 row in set (0.00 sec)

PHP script

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>example-encode() - php mysql examples | w3resource</title>
</head>
<body>
<?php
echo "<h2>Encrypting the string 'mytext' : </h2>";
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='100' align='center'>ENCODE('mytext','mykeystring')</td>";
echo "</tr>";
include("../dbopen.php");
$result = mysql_query("SELECT ENCODE('mytext','mykeystring')");
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td align='center' width='200'>" . $row["ENCODE('mytext','mykeystring')"] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

View the example in browser

Example: MySQL encode() function using table

Sample table: testtable


Code:

INSERT INTO testtable VALUE(ENCODE('myencodetext','mypassw'));

Explanation

The above MySQL statement inserts encrypted data into table 'testtable'.

Sample Output:

mysql> INSERT INTO testtable VALUE(ENCODE('myencodetext','mypassw'));
Query OK, 1 row affected (0.00 sec)

Previous: DES_ENCRYPT()
Next: ENCRYPT()