Swedish characters in php/MySQL site

Hi there

How can I store and display swedish characters e.g. the o with the dots on it and the a with the arrows etc. in a mysql database, and make it render properly in a browser via PHP?

Also would like to be able to edit database fields via HTML textfield and textarea controls and have the information populate correctly back into the database.

Any guidance would be gratefully received!

Many thanks
LVL 1
butterhookAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dsmileCommented:
All you need is to create insert/update & display pages with same charset (I recommend utf-8).
If you do so, I guarantee 100% that swedish characters can be stored and retrieved as normal as english characters :)

I attach sample code that proves what I'm saying.

This is test schema

CREATE TABLE test_sw (
  id int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  KEY id (id)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title> Test Swedish page </title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

 </head>

 <body>
<?php
$host = 'localhost'; $db_user = 'root'; $db_password = '';
$database = 'test';
$connect = mysql_connect ( $host, $db_user, $db_password );
mysql_select_db ( $database );

if (isset($_POST['submit'])) {
	$result = mysql_query("INSERT INTO test_sw (id, name) VALUES ('', '".$_POST['name']."')");
	if (!$result) {
	   echo 'Could not run query: ' . mysql_error();
	   exit;
	}
}

$result = mysql_query('SELECT id, name FROM test_sw');
if (!$result) {
   echo 'Could not run query: ' . mysql_error();
   exit;
}

while ($row = mysql_fetch_array($result)) {
   echo 'string #'. $row['id'] .': '. $row['name'] .'<br />';
}

?>
<form method="post" action="?">
	<input type="text" name="name" size="50" maxlength="255"></input> <input type="submit" name="submit" value="Insert">
</form>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
max-hbCommented:
Hi!
You probably want to set your client-server connection encoding to utf8 as well:
Insert the following at line 14 of the above script.

mysql_query('SET NAMES utf8');
0
Ray PaseurCommented:
Here is a script you can install and test with.  No mention of UTF-8 anywhere.  In fact, if activate line 40, the special characters will come back out as questionmarks.
<?php // RAY_accented_chars.php
error_reporting(E_ALL);


// IMPORTANT PAGES FROM THE MANUALS
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR DBA / HOSTING PROVIDER
$db_user = "??";
$db_word = "??";


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
if (!$dbcx = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $dbcx))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES


// DO NOT MOVE TO UTF-8
// if (!mysql_query('SET NAMES utf8')) die(mysql_error());


// CREATE A TABLE TO TEST WITH
$sql = "CREATE TEMPORARY TABLE my_table (
        _key INT         NOT NULL AUTO_INCREMENT,
        name VARCHAR(32) NOT NULL DEFAULT '',
        PRIMARY KEY(_key)
        ) ";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}



// ESCAPING A DATA FIELD FOR USE IN MYSQL QUERIES
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
$names[] = mysql_real_escape_string("O'Réilly");
$names[] = mysql_real_escape_string("ENCYCLOPÆDIA");
$names[] = mysql_real_escape_string("Umlöut");
$names[] = mysql_real_escape_string("€uro");


foreach ($names as $name)
{
    // MAKING AN INSERT QUERY, USING THE ESCAPED STRING AND TESTING THE RESULTS
    $sql = "INSERT INTO my_table (name) VALUES ('$name')";
    $res = mysql_query($sql);

    // IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
    if (!$res)
    {
        $errmsg = mysql_errno() . ' ' . mysql_error();
        echo "<br/>QUERY FAIL: ";
        echo "<br/>$sql <br/>";
        die($errmsg);
    }
    // IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS

    // GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED
    // MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php
    $_key  = mysql_insert_id();

    echo "<br/>KEY: $_key AND NAME WITH ESCAPE STRING INCLUDED: $name ";
}


// MAKING A SELECT QUERY AND TESTING THE RESULTS
$sql = "SELECT * FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS


// ITERATE OVER THE RESULTS SET
echo "<pre>";
while ($row = mysql_fetch_assoc($res))
{
    var_dump($row);
}

Open in new window

0
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

Ray PaseurCommented:
This part, however, may present a bit of a challenge: "...edit database fields via HTML textfield and textarea controls..."

There are no keys for some of those things on my keyboard.  I used a clip library with copy/paste to create the script above.  When I typed the Euro symbol directly into the browser string, it got urlencoded into a numeric entity.  These produce equivalent outputs

http://www.laprbass.com/RAY_bounce_get.php?q=€
http://www.laprbass.com/RAY_bounce_get.php?q=%80

Using this code below, I was able to paste the Euro and other things into the text box.  It came through fine.

HTH, ~Ray
<?php // RAY_post_example.php
error_reporting(E_ALL);
echo "<pre>\n"; // MAKE IT EASY TO READ



// THIS ILLUSTRATES THE RELATIONSHIP BETWEEN THE 'ACTION' AND THE 'FORM' WHEN COMBINED INTO A SINGLE PHP SCRIPT FILE



// SET A DEFAULT VALUES FOR A VARIABLE TO PREPOPULATE THE FORM - THIS COULD COME FROM A DATA BASE, OR MIGHT BE EMPTY
$my_INPUT_Field = 'ORIGINAL DATA';

// IF THE FORM WAS FILLED IN, COPY THE INPUT INTO OUR VARIABLE
if (!empty($_POST["my_INPUT_Field"]))
{
    $my_INPUT_Field = $_POST["my_INPUT_Field"];
}


// HAS ANYTHING BEEN POSTED - IF SO, $_POST IS SET AND CONTAINS THE DATA
if (!empty($_POST))
{
    // SHOW THE POST ARRAY
    var_dump($_POST);
}
// THIS IS THE END OF THE ACTION SCRIPT




// THIS IS THE FORM SCRIPT - FOR CONVENIENCE WE DROP OUT OF PHP INTO HTML
?>
<form method="post">
TYPE SOMETHING HERE:
<input type="text"   name="my_INPUT_Field"   value="<?php echo $my_INPUT_Field; ?>" />
<input type="submit" name="my_SUBMIT_Button" value="go" />
</form>

Open in new window

0
Shinesh PremrajanEngineering ManagerCommented:
You need to place this in your script for the utf 8 to work as you are expecting.

hope this helps

$mysql_link = mysql_connect($host, $username, $password);
mysql_select_db($database, $mysql_link); 
mysql_query(‘SET character_set_results=utf8');
mysql_query(‘SET names=utf8');
mysql_query(‘SET character_set_client=utf8');
mysql_query(‘SET character_set_connection=utf8');
mysql_query(‘SET character_set_results=utf8');
mysql_query(‘SET collation_connection=utf8_general_ci’);

Open in new window

0
butterhookAuthor Commented:
Great work fellers
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.