etsp каза:
Radko каза:
etsp каза:
Това е линка след промените по енкодинга ... Пробвах всичко, но пак не става.
http://dox.bg/files/dw?a=87191fba4b
Ако енкодинга на файловете е бил един преди това, и после си го сменил на UTF-8 without BOM, трябва отново да си пренапишеш кирилицата във файловете, няма как от ?????? магически да ти се прехвърли на кирилица.
dakata__92 каза:
Щом си пипал чарсета и е настроен на utf-8, базата ти е настроена остава само да си ПРЕЗАПИШЕШ енкодинга на самия файл на UTF-8, не на ANSI или без BOOM
Пробвах всички варианти с/без боом, генегали, уникодове

всичко без ефект ?
В базата данни, където се пази информацията, е на български. В самия код използвам сторед процедури и там нещо се обърква. Иначе по кода няма директно подаване на БГ символи. ( никой май не е погледнал кода )
ЕТО МАЛКО ПО-ПОДРОБНО ОБЯСНЕНИЕ НА ПРОБЛЕМЪТ И ВСИЧКИ ДЕТАЙЛИ КЪМ НЕГО:
В Базата данни имам:
Stored процедурата catalog_get_departments_list, връща ID и името на категорията от таблица departament. PhP скрипта "ще накара" тази сторед процедура да генерира списъка с категории.
CREATE PROCEDURE catalog_get_departments_list()
BEGIN
SELECT department_id, name FROM department ORDER BY department_id;
END$
-- Create deparment table
CREATE TABLE `department` (
`department_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`description` VARCHAR(1000),
PRIMARY KEY (`department_id`)
) ENGINE=MyISAM;
department таблицата е с категориите!
В тази таблица съм сложил информация на български, като я отворя през php MyAdmin, тази информация се чете ясно (няма маймуница или ????? ) Там нямам проблем
Проблемът е следния:След като заредя главната страница, списъкът с категориите ми излиза с ??????? ( информацията от БД, която е съхранена там на български не може да се изведе [ако е на англйски нямам този проблем])
Базата данни е utf8_unicode_ci, таблицата е с колация utf8_unicode_ci. Пробвал съм всички варианти на промяна utf8_general_ci, cp1251… .Всички .php, .tpl файлове съм ги правил и в двата варианта: encoding UTF8 и UTF8 without BOM.
Без никакъв ефект.
Слагал съм в началото на всички .php, .tpl файлове
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
и
</html> mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER_SET utf8'); , но пак без ефект!
Оформлението и представянето в проекта се генерира посредством Smarty шаблони за дизайн.
(използвам .php и .tpl) Когато в даден .tpl файл имам директно информация на българси (без предаване чрез обекти....) ТЯ СЕ ВИЗУАЛИЗИРА КОРЕКТНО НА ГЛАВНАТА СТРАНИЦА. А там където се извлича от базата я дава като ???? По-надолу в кодът съм посочил това нещо
С този проблем се мъча от доста време. Някой може ли да помогне?
Благодаря!
Ето линк със всички файлове за по-лесно: http://dox.bg/files/dw?a=9f91504699
По-долу са посочени и поотделно:
index.php
<?php
// Include utility files
require_once 'include/config.php';
require_once BUSINESS_DIR . 'error_handler.php';
// Set the error handler
ErrorHandler::SetHandler();
// Load the application page template
require_once PRESENTATION_DIR . 'application.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'catalog.php';
// Load Smarty template file
$application = new Application();
// Display the page
$application->display('store_front.tpl');
// Close database connection
DatabaseHandler::Close();
?>
Идеята е:
Smarty template файлът (departments_list.tpl) и plug-in файла ((presentation/smarty_plugins/function.load_presentation_object. php) работят заедно за генерирането на листа с категории.
Обработката започва в function.load_presentation_object.php, която е включена в store_
front.tpl файл. Първа линия в departments_list.tpl зарежда DepartmentList обект
чрез Smarty плъг-ин: {load_presentation_object filename = "departments_list" Assign = "obj"}
Smarty_function_load_presentation_object () плъг-ин функция създава и инициализира
DepartmentsList обект (този клас е включена презентация / departments_list.php), което е
присвоява на OBJ променлива, достъпни от Smarty дизайн шаблон файл:
function.load_presentation_object.php
<?php
// Plug-in functions inside plug-in files must be named: smarty_type_name
function smarty_function_load_presentation_object($params, $smarty)
{
require_once PRESENTATION_DIR . $params['filename'] . '.php';
$className = str_replace(' ', '',
ucfirst(str_replace('_', ' ',
$params['filename'])));
// Create presentation object
$obj = new $className();
if (method_exists($obj, 'init'))
{
$obj->init();
}
// Assign template variable
$smarty->assign($params['assign'], $obj);
}
?>
Init () методът в DepartmentsList наследява член на класа ($ mDepartments) с
масив, съдържащ списъка на категориите и друг public член, съдържащ индекса на избраната в момента категория ($ mSelectedDepartment).
вътре в HTML кода, който формира оформлението на Smarty шаблон ( / departments_list.tpl), можете да видите Smarty тагове, които правят:
{* departments_list.tpl *}
{load_presentation_object filename="departments_list" assign="obj"}
{* Start departments list *}
<div class="box">
<p class="box-title">Choose a Department</p>
<ul>
{* Loop through the list of departments *}
{section name=i loop=$obj->mDepartments}
{assign var=selected value=""}
{* Verify if the department is selected to decide what CSS style
to use *}
{if ($obj->mSelectedDepartment ==$obj->mDepartments
.department_id)}
{assign var=selected value="class="selected""}
{/if}
<li>
{* Generate a link for a new department in the list *}
<a {$selected} href="{$obj->mDepartments.link_to_department}" >
{$obj->mDepartments.name}
</a>
</li>
{/section}
</ul>
</div>
{* End departments list *}
departments_list.php
<?php
// Manages the departments list
class DepartmentsList
{
/* Public variables available in departments_list.tpl Smarty template */
public $mSelectedDepartment = 0;
public $mDepartments;
// Constructor reads query string parameter
public function __construct()
{
/* If DepartmentId exists in the query string, we're visiting a
department */
if (isset ($_GET['DepartmentId']))
$this->mSelectedDepartment = (int)$_GET['DepartmentId'];
}
/* Calls business tier method to read departments list and create
their links */
public function init()
{
// Get the list of departments from the business tier
$this->mDepartments = Catalog::GetDepartments();
// Create the department links
for ($i = 0; $i < count($this->mDepartments); $i++)
$this->mDepartments[$i]['link_to_department' ] =
'index.php?DepartmentId=' . $this->mDepartments[$i]['department_id'];
}
}
?>
store_front.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>YUI Base Page</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/2.8.0r4/build/reset-fonts- grids/reset-fonts-grids.css" type="text/css">
</head>
<body class="yui-skin-sam">
<div id="doc3" class="yui-t3">
<div id="hd" role="banner"><h1>Header</h1></div>
<div id="bd" role="main">
<div id="yui-main">
<div class="yui-b"><div class="yui-g">
</div>
<div class="yui-g">
</div>
</div>
</div>
<div class="yui-b"></div>
</div>
<div id="ft" role="contentinfo"><p>Footer</p>< /div>
</div>
</body>
</html>
store_front.tpl
{* smarty *}
{config_load file="site.conf"}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html>
<head>
<title>{#site_title#}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" rel="stylesheet" href="styles/tshirtshop.css" />
</head>
<body>
<div id="doc" class="yui-t2">
<div id="bd">
<div id="yui-main">
<div class="yui-b">
<div id="header" class="yui-g">
<a href="index.php">
<img src="images/tshirtshop.tif" alt="tshirtshop logo" />
</a>
</div>
<div id="contents" class="yui-g">
Категории
</div>
</div>
</div>
<div class="yui-b">
{include file="departments_list.tpl"}
</div>
</div>
</div>
</body>
</html>
ТУК КАКТО Е В КОДА "Категории" СЕ ВИЗУАЛИЗИРА НА ГЛАВНАТА СТАНИЦА, НО САМО ИМЕТО Категории БЕЗ ДА ИЗЛИЗАТ СЪХРАНЕНИЕТЕ В ДБ НА БЪЛГАРСКИ КАТЕГОРИИ
DatabaseHandler ще съхранява общата функционалност, която ще се ползва повторно, когато
има нужда от достъп до базата данни. Като този вид функционалност, свързани в
отделен клас, спестява натиснатите клавиши и избягва грешки в дългосрочен план.<br style="mso-special-character:line-break"> <br style="mso-special-character:line-break">
database_handler.php
<?php
// Class providing generic data access functionality
class DatabaseHandler
{
// Hold an instance of the PDO class
private static $_mHandler;
// Private constructor to prevent direct creation of object
private function __construct()
{
}
// Return an initialized database handler
private static function GetHandler()
{
// Create a database connection only if one doesn't already exist
if (!isset(self::$_mHandler))
{
// Execute code catching potential exceptions
try
{
// Create a new PDO class instance
self::$_mHandler =
new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD,
array(PDO::ATTR_PERSISTENT => DB_PERSISTENCY));
// Configure PDO to throw exceptions
self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
}
// Return the database handler
return self::$_mHandler;
}
// Wrapper method for PDOStatement::execute()
public static function Execute($sqlQuery, $params = null)
{
// Try to execute an SQL query or a stored procedure
try
{
// Get the database handler
$database_handler = self::GetHandler();
// Prepare the query for execution
$statement_handler = $database_handler->prepare($sqlQuery);
// Execute query
$statement_handler->execute($params);
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
}
// Wrapper method for PDOStatement::fetchAll()
public static function GetAll($sqlQuery, $params = null,
$fetchStyle = PDO::FETCH_ASSOC)
{
// Initialize the return value to null
$result = null;
// Try to execute an SQL query or a stored procedure
try
{
// Get the database handler
$database_handler = self::GetHandler();
// Prepare the query for execution
$statement_handler = $database_handler->prepare($sqlQuery);
// Execute the query
$statement_handler->execute($params);
// Fetch result
$result = $statement_handler->fetchAll($fetchStyle);
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
// Return the query results
return $result;
}
// Wrapper method for PDOStatement::fetch()
public static function GetRow($sqlQuery, $params = null,
$fetchStyle = PDO::FETCH_ASSOC)
{
// Initialize the return value to null
$result = null;
// Try to execute an SQL query or a stored procedure
try
{
// Get the database handler
$database_handler = self::GetHandler();
// Prepare the query for execution
$statement_handler = $database_handler->prepare($sqlQuery);
// Execute the query
$statement_handler->execute($params);
// Fetch result
$result = $statement_handler->fetch($fetchStyle);
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
// Return the query results
return $result;
}
// Return the first column value from a row
public static function GetOne($sqlQuery, $params = null)
{
// Initialize the return value to null
$result = null;
// Try to execute an SQL query or a stored procedure
try
{
// Get the database handler
$database_handler = self::GetHandler();
// Prepare the query for execution
$statement_handler = $database_handler->prepare($sqlQuery);
// Execute the query
$statement_handler->execute($params);
// Fetch result
$result = $statement_handler->fetch(PDO::FETCH_NUM);
/* Save the first value of the result set (first column of the first row)
to $result */
$result = $result[0];
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
// Return the query results
return $result;
}
// Clear the PDO class instance
public static function Close()
{
self::$_mHandler = null;
}
}
?>
GetDepartments () е метод, който ще изведе списък на категориите от базата данни.
catalog.php
<?php
// Business tier class for reading product catalog information
class Catalog
{
// Retrieves all departments
public static function GetDepartments()
{
// Build SQL query
$sql = 'CALL catalog_get_departments_list()';
// Execute the query and return the results
return DatabaseHandler::GetAll($sql);
}
}
?>
application.php
<?php
// Reference Smarty library
require_once SMARTY_DIR . 'Smarty.class.php';
/* Class that extends Smarty, used to process and display Smarty
files */
class Application extends Smarty
{
// Class constructor
public function __construct()
{
// Call Smarty's constructor
parent::Smarty();
// Change the default template directories
$this->template_dir = TEMPLATE_DIR;
$this->compile_dir = COMPILE_DIR;
$this->config_dir = CONFIG_DIR;
$this->plugins_dir[0] = SMARTY_DIR . 'plugins';
$this->plugins_dir[1] = PRESENTATION_DIR . 'smarty_plugins';
}
}
?>