TrinityTuts

Save unicode data in Mysql using PHP

Last updated on January 8th, 2020 at 10:17 pm

In this post i will explain you how to save unicode data to mysql database using php. Saving a unicode data to mysql database is not easy task for beginners. whenever we can post unicode data from form and save it to database using php it save like this format :-

But we need to save data into original format as shown below :-

Now here is a solution to solve this problem and save unicode to database.

Database:
Create a sample database ‘unicode’ where we can save data

CREATE TABLE IF NOT EXISTS `data` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `data` text CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

When we create a table for saving unicode we can set unicode data field character to utf8_general_ci as in above mysql query.

index.php

<html>
<head>
	<title>Welcome to trinity tuts</title>
</head>

<body>
	<form method="post" action="unicode.php">
		<div>
			<label>Unicode: </label>
			<textarea name="unicode"></textarea>
		</div>
		<div>
			<input type="submit">
		</div>
	</form>
</body>
</html>

In this page i create a simple form through which i send data to php page and save to database.

unicode.php

<?php
/* Connection */
$conn = mysql_connect("localhost", "root", "");
mysql_set_charset('utf8', $conn);  // Most important steps
mysql_select_db("unicode", $conn);

if(isset($_POST['unicode']) && (!empty($_POST['unicode']))){
	
	$data = mysql_real_escape_string($_POST['unicode']);
	$qur = mysql_query("insert into data set data='$data'", $conn);
	if($qur){
		echo 'Data inserted to database!<br>';
		// Display inserted data
		$dip = mysql_query("select * from data", $conn);
		while($get = mysql_fetch_array($dip)){
			extract($get);
			echo $get['data'].'<br>';
		}
	}else{
		echo 'Error inserting data to database!.';
	}
}

In above almost code is same we normally use to save data to database but we need to add

mysql_set_charset('utf8', $conn);  // Most important steps

this line of code after we create connection to mysql and when we can save data or perform insert operation over database we need to pass connection parameter to database

$qur = mysql_query("insert into data set data='$data'", $conn);

Thank you
Happy coding.