MySQL / PHP多语言表单

时间:2015-11-06 13:30:24

标签: php mysql pdo translation

如何使用pdo对象从数据库翻译构建多语言表单?

例如,有我的代码来创建pdo对象:

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname",$username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMEssage();
    die();
}

$sql = "SELECT FROM `lang_content` `id`, `:lang`";
$query = $pdo->prepare($sql);

if($query->execute(array(
        ':lang' => $_GET['lang'].'_content'
    ))){
    // Show content
}

MySQL表结构:

CREATE TABLE `lang_content` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `en_content` VARCHAR(1000) NULL DEFAULT NULL,
    `lv_content` VARCHAR(1000) NULL DEFAULT NULL,
    `ru_content` VARCHAR(1000) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
COMMENT='All translations'
ENGINE=MyISAM
;

MySQL表数据示例:

id  en_content  lv_content  ru_content
1   MOD         KASKO       КАСКО
2   MTPL        OCTA        ОСАГО

我想用它像: 如果lang en

<?= $result->1 ?> // Echo MOD

将返回MOD,

<?= $result->2 ?> // Echo MTPL

将返回MTPL

1 个答案:

答案 0 :(得分:0)

老实说,通过数据库进行翻译并不是一种好的做法。许多大平台通过某种文本格式来实现。例如,magento通过csv文件来完成它。

您可以使用以下代码开始开发。

您的西班牙语翻译文件es.csv

'Home', 'Inicio'
'Page 1', 'Pagina 1'
'Page 2', 'Pagina 2'
'Page 3', 'Pagina 3'

第一列单词将是您在函数中定义的默认语言。

<a href="#"><?php __("Home"); ?>

然后,您将使用类似于顶部的switch语句来捕获用户选择的语言。 __()函数看起来像这样。输入将是“家”

$csv = array_map('str_getcsv', file($file));
// Logic (where it would do the translation)
// It could look for the input in the $cvs variable if it exist then use the next value of the current array. Else keep the text the same.

您的cvs文件需要制作要翻译的确切字词。

相关问题