Posts UTF8 Encoding ... you, uh, you, uh
Post
Cancel

UTF8 Encoding ... you, uh, you, uh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//src - https://nabeel.molham.me/blog/php-best-practices-in-arabic/
<?php
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding( 'UTF-8' );

// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output( 'UTF-8' );

// Our UTF-8 test string
$string = 'مصر';

// Transform the string in some way with a multibyte function
// Note how we cut the string at a non-Ascii character for demonstration purposes
$string = mb_substr( $string, 0, 15 );

// Connect to a database to store the transformed string
// See the PDO example in this document for more information
// Note that we define the character set as utf8mb4 in the PDO connection string
$link = new \PDO( 'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
                    'your-username',
                    'your-password',
                    array (
                        \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                        \PDO::ATTR_PERSISTENT => false
                    )
        );

// Store our transformed string as UTF-8 in our database
// Your DB and tables are in the utf8mb4 character set and collation, right?
$handle = $link->prepare( 'insert into countries (ID, name) values (?, ?)' );
$handle->bindValue( 1, 1, PDO::PARAM_INT );
$handle->bindValue( 2, $string );
$handle->execute();

// Retrieve the string we just stored to prove it was stored correctly
$handle = $link->prepare( 'select * from countries where Id = ?' );
$handle->bindValue( 1, 1, PDO::PARAM_INT );
$handle->execute();

// Store the result into an object that we'll output later in our HTML
$result = $handle->fetchAll( \PDO::FETCH_OBJ );

// doctype right after php closing tag
?><!doctype html>

        <?php
        foreach( $result as $row )
    {
            echo $row->name, '  
';
        }
        ?>

origin - http://www.pipiscrew.com/?p=8440 utf8-encoding-you-uh-you-uh

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags