When i login to my drupal page. It’s showing the following error
Parse error: syntax error, unexpected '<' in /document_root/sites/all/modules/rules/rules/modules/php.rules.inc(107) :
eval()’d code on line 1
When i just figure out to the particular page there is no problem in that function . Below is the function where the error marked..
function rules_php_eval_return($code, $arguments = array()) {
extract($arguments);
return eval($code);
}
Could any one can suggest me what’s the problem may be!! It’s drupal 6.x version.
asked Jun 7, 2011 at 13:20
7
I came accross an error like this when I pasted a PHP code snippet from the Drupal site into a block to show submenus. These submenus were detected and assigned in a foreach loop, but since there weren’t any submenus, the menu variable remained unassigned and thus undeclared as well.
My obvious solution was to assign an empty string to the menu variable before the foreach loop.
answered Oct 11, 2012 at 18:20
I don’t know drupal, but i think that $code contains something like :
$code = '<?php $someCode;';
eval($code);
//Produces : Parse error: syntax error, unexpected '<' in file(1) : eval()'d code on line 1
The error is telling you that $code contains a parse error (maybe the phptag)
You an echo $code to check what’s wrong.
answered Jun 7, 2011 at 13:57
Gérald CroësGérald Croës
3,7892 gold badges18 silver badges20 bronze badges
eval’d usually comes when bad custom php codes embeded in site using php module(php filter)
If you can access site in anyway, go to Triggered Rules and Rule Sets page and find if any rule is firing a custom php code.
It’s idiot’s style to put php codes in Rules. Either you should create a module or use Rules itself
If you can’t access the site, go to /modules folder and move the «php» folder somewhere else. Then you will be able to access site. Quickly remove buggy code and replace the folder.
Then, start debugging it.
answered Jun 10, 2011 at 21:11
AKSAKS
4,5982 gold badges29 silver badges48 bronze badges
I just had this same problem trying to process data returned from an HTTP request. I was using simplexml_load_string, but the HTTP response was an error, so the data was not formatted as XML, thus causing simplexml to error (propogate up). My message was the same as yours, «error in file on line X; eval’d() code on line X». So, it may not necessarily be an error within your code, or even the eval’d code.
While it looks like you don’t have the following issue, it is something to keep in mind as well. When declaring variables within the eval’d code they will scope the same as if inline in the file. Similarly, variables preceding the eval’d code are available within it, and may cause collisions, or inadvertent re-assigning (eg. $i in nested loops).
answered Nov 19, 2012 at 14:32
Wayne WeibelWayne Weibel
9331 gold badge14 silver badges22 bronze badges
I got carried away and have thought about how to improve it this might not actually be an answer to your question but more of a food-for-thought. I see two solutions, and both are kind of invasive.
Of course both solutions only work in all the cases if your formula only use «variables» like in your example with ((WILL*0.8)/2.5)+(LEVEL/4)
. If you have more complex formulas you’d have do adapt my solutions.
Wrapping eval and don’t inject all the inputs in the eval’d code
Assuming the formulas are under your control and not user-supplied you could improve your eval by not injecting all the inputs in your eval’d code but only the formula. This way you don’t have to escape the inputs, you only have to make sure the formula is syntactically correct.
function calculateFormula($_vars, $_values, $_formula) {
// This transforms your formula into PHP code which looks
// like this: (($WILL*0.8)/2.5)+($LEVEL/4)
$_cleanFormula = str_replace(
$_vars,
array_map(function($v) { return '$' . $v; }, $_vars),
$_formula
);
// create the $WILL, $LEVEL, $IQ and $EXP variables in the local scope
extract(array_combine($_vars, $_values));
// execute the PHP-formula
return eval('return ' . $_cleanFormula . ';');
}
// Use it like this, instead of eval
$sucrate = calculateFormula(
array("LEVEL", "EXP", "WILL", "IQ"),
array($player['level'], $player['exp'], $player['will'], $player['IQ']),
$r['crimePERCFORM']);
This still uses eval, so security-wise this would be the worst solution. But this would be the closest to what you have now.
Using Symfony’s Expression Language
The more secure option would be to use something like the symfony’s expression language component. Now you don’t need the whole symfony framework in your application, the expression language component can be used on it’s own. This could be a big change, this depends on how your existing codebase looks. If you have not used composer or namespaces in your project, this change might be too big.
require_once __DIR__ . '/vendor/autoload.php';
use SymfonyComponentExpressionLanguageExpressionLanguage;
$expressionLanguage = new ExpressionLanguage();
$sucrate = $expressionLanguage->evaluate(
$r['crimePERCFORM'],
array(
"LEVEL" => $player['level'],
"EXP" => $player['exp'],
"WILL" => $player['will'],
"IQ" => $player['IQ'],
)
);
As I’ve said this is maybe a huge change and you might have to get acquainted with composer if you don’t know it already.
(PHP 4, PHP 5, PHP 7, PHP
eval — Выполняет код PHP, содержащейся в строке
Описание
eval(string $code
): mixed
Предостережение
Языковая конструкция eval() может быть очень
опасной, поскольку позволяет выполнить произвольный код.
Использование данной функции не рекомендуется. Если вы
полностью убеждены, что нет другого способа, кроме использования этой конструкции,
обратите особое внимание на то, чтобы не передавать какие-либо данные, предоставленные
пользователем, без предварительной проверки.
Список параметров
-
code
-
Выполняемая строка кода PHP.
Код не должен быть обёрнут открывающимся и закрывающимся
тегами PHP, то есть
строка должна быть, например, такой'echo "Привет!";'
,
но не такой'<?php echo "Привет!"; >'
.
Возможно переключаться между режимами PHP- и HTML-кода, например
'echo "Код PHP!"; ?>Код HTML<?php echo "Снова код PHP!";'
.Передаваемый код должен быть верным исполняемым кодом PHP. Это значит, что
операторы должны быть разделены точкой с запятой (;).
При исполнении строки'echo "Привет!"'
будет сгенерирована ошибка,
а строка'echo "Привет!";'
будет успешно выполнена.Указание в коде ключевого слова
return
прекращает
исполнение кода в строке.Исполняемый код из строки будет выполняться в области видимости кода, вызвавшего
eval(). Таким образом, любые переменные, определённые или
изменённые в вызове eval(), будут доступны после его
выполнения в теле программы.
Возвращаемые значения
Функция eval() возвращает null
, если не вызывается
return
, в случае чего возвращается значение, переданное
return
. С PHP 7, если в исполняемом коде присутствует ошибка, то
eval() вызывает исключение «ParseError». До PHP 7 в этом случае
возвращается false
и продолжается нормальное
выполнение последующего кода. Невозможно поймать ошибку парсера в eval(),
используя set_error_handler().
Примеры
Пример #1 Пример функции eval() — простое слияние текста
<?php
$string = 'чашка';
$name = 'кофе';
$str = 'Это $string с моим $name.';
echo $str. "n";
eval("$str = "$str";");
echo $str. "n";
?>
Результат выполнения данного примера:
Это $string с моим $name. Это чашка с моим кофе.
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.
Подсказка
Как и с любой другой функцией, осуществляющей вывод непосредственно в браузер, вы можете использовать функции контроля вывода, чтобы перехватывать выводимые этой функцией данные и сохранять их, например, в строку (string).
Замечание:
В случае фатальной ошибки в исполняемом коде прекращается исполнение всего скрипта.
Смотрите также
- call_user_func() — Вызывает callback-функцию, заданную в первом параметре
Anonymous ¶
18 years ago
Kepp the following Quote in mind:
If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP
Jeremie LEGRAND ¶
5 years ago
At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
<?php
@eval('$content = (100 - );');
?>
(Even if it is in the man, I'm note sure it acted like this in 5.6, but whatever)
To catch it, I had to do:
<?php
try {
eval('$content = (100 - );');
} catch (Throwable $t) {
$content = null;
}
?>
This is the only way I found to catch the error and hide the fact there was one.
lord dot dracon at gmail dot com ¶
7 years ago
Inception with eval()
<pre>
Inception Start:
<?php
eval("echo 'Inception lvl 1...n'; eval('echo "Inception lvl 2...n"; eval("echo 'Inception lvl 3...n'; eval('echo \"Limbo!\";');");');");
?>
remindfwd ¶
2 years ago
Note that
<?phpecho eval( '$var = (20 - 5);' ); // don't show anythingecho ' someString ' . eval( 'echo $var = 15;' ); // outputs 15 someString
//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString '; // 15 someString otherString
//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString ' . '...' .eval( 'echo " __ " . $var = 10;' ); // 15 __ 10 someString otherString ...?>
catgirl at charuru dot moe ¶
5 years ago
It should be noted that imported namespaces are not available in eval.
bohwaz ¶
11 years ago
If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this:
<?php
$test
= '2+3*pi';// Remove whitespaces
$test = preg_replace('/s+/', '', $test);$number = '(?:d+(?:[,.]d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+/*^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'s*((?1)+)|((?1)+))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patternsif (preg_match($regexp, $q))
{
$test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
eval('$result = '.$test.';');
}
else
{
$result = false;
}?>
I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error.
solobot ¶
5 years ago
eval() is workaround for generating multiple anonymous classes with static properties in loop
public function generateClassMap()
{
foreach ($this->classMap as $tableName => $class)
{
$c = null;
eval('$c = new class extends commonMyStaticClass {
public static $tableName;
public static function tableName()
{
return static::$tableName;
}
};');
$c::$tableName = $this->replicationPrefix.$tableName;
$this->classMap[$tableName] = $c;
}
}
thus every class will have its own $tableName instead of common ancestor.
darkhogg (foo) gmail (bar) com ¶
13 years ago
The following code
<?php
eval( '?> foo <?php' );
?>
does not throw any error, but prints the opening tag.
Adding a space after the open tag fixes it:
<?php
eval( '?> foo <?php ' );
?>
xxixxek at gmail dot com ¶
3 months ago
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:
$res = eval($somecode);
if(!$res) {
echo "<pre>";
print_r(explode(PHP_EOL, $somecode));
echo "</pre>";
}
I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
xxixxek at gmail dot com ¶
3 months ago
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:
$res = eval($somecode);
if(!$res) {
echo "<pre>";
print_r(explode(PHP_EOL, $somecode));
echo "</pre>";
}
I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
stocki dot r at gmail dot com ¶
1 year ago
You can use `eval()` to combine classes/traits dynamically with anonymus classes:
<?phpfunction init($trait, $class) {
return (trait_exists($trait) && class_exists($class))
? eval("return new class() extends {$class} { use {$trait}; };")
: false;
}
trait
Edit {
function hello() { echo 'EDIT: ' . $this->modulename; }
}
trait Ajax {
function hello() { echo 'AJAX: ' . $this->modulename; }
}
class MyModule {
public $modulename = 'My Module';
}
class AnotherModule {
public $modulename = 'Another Module';
}init('Edit', 'MyModule')->hello(); # 'EDIT: My Module'
init('Ajax', 'AnotherModule')->hello(); # 'AJAX: Another Module'?>
greald at gmail dot com ¶
1 year ago
to avoid the evil eval() you may use the fact that function names, variable names, property names and method names can be handled strings.
<?php
class Fruit
{
public $tomato = "Tomatos";
public function
red() {return " are red. ";}
}$fruit = new Fruit;
$fruitStr = "tomato";
$colorStr = "red";
echo
$fruit->$fruitStr . $fruit->$colorStr();// and procedural //////////////////////////////////////////$lemon = "Lemons";
function
yellow() {return " are yellow. ";}$fruitStr = "$lemon";
$colorStr = "yellow";
echo
$fruitStr . $colorStr();
?>
divinity76 at gmail dot com ¶
6 years ago
imo, this is a better eval replacement:
<?php
function betterEval($code) {
$tmp = tmpfile ();
$tmpf = stream_get_meta_data ( $tmp );
$tmpf = $tmpf ['uri'];
fwrite ( $tmp, $code );
$ret = include ($tmpf);
fclose ( $tmp );
return $ret;
}
?>
- why? betterEval follows normal php opening and closing tag conventions, there's no need to strip `<?php?>` from the source. and it always throws a ParseError if there was a parse error, instead of returning false (note: this was fixed for normal eval() in php 7.0). - and there's also something about exception backtraces
Karel ¶
8 years ago
For them who are facing syntax error when try execute code in eval,
<?php
$str
= '<?php echo "test"; ?>';
eval(
'?>'.$str.'<?php;'); // outputs test
eval('?>'.$str.'<?'); // outputs test
eval('?>'.$str.'<?php');// throws syntax error - unexpected $end
?>
Uther ¶
7 years ago
eval'd code within namespaces which contain class and/or function definitions will be defined in the global namespace... not incredibly obvious :/
php at rijkvanwel dot nl ¶
12 years ago
To catch a parse error in eval()'ed code with a custom error handler, use error_get_last() (PHP >= 5.2.0).
<?php
$return = eval( 'parse error' );
if (
$return === false && ( $error = error_get_last() ) ) {
myErrorHandler( $error['type'], $error['message'], $error['file'], $error['line'], null );// Since the "execution of the following code continues normally", as stated in the manual,
// we still have to exit explicitly in case of an error
exit;
}
?>
php at stock-consulting dot com ¶
14 years ago
Magic constants like __FILE__ may not return what you expect if used inside eval()'d code. Instead, it'll answer something like "c:directoryfilename.php(123) : eval()'d code" (under Windows, obviously, checked with PHP5.2.6) - which can still be processed with a function like preg_replace to receive the filename of the file containing the eval().
Example:
<?php
$filename = preg_replace('@(.*(.*$@', '', __FILE__);
echo $filename;
?>
marco at harddisk dot is-a-geek dot org ¶
14 years ago
eval does not work reliably in conjunction with global, at least not in the cygwin port version.
So:
<?PHP
class foo {
//my class...
}
function load_module($module) {
eval("global $".$module."_var;");
eval("$".$module."_var=&new foo();");
//various stuff ... ...
}
load_module("foo");
?>
becomes to working:
<?PHP
class foo {
//my class...
}
function load_module($module) {
eval('$GLOBALS["'.$module.'_var"]=&new foo();');
//various stuff ... ...
}
load_module("foo");
?>
Note in the 2nd example, you _always_ need to use $GLOBALS[$module] to access the variable!
Ipseno at yahoo dot com ¶
15 years ago
If you attempt to call a user defined function in eval() and .php files are obfuscated by Zend encoder, it will result in a fatal error.
Use a call_user_func() inside eval() to call your personal hand made functions.
This is user function
<?phpfunction square_it($nmb)
{
return $nmb * $nmb;
}?>
//Checking if eval sees it?
<?php
$code
= var_export( function_exists('square_it') );
eval(
$code ); //returns TRUE - so yes it does!?>
This will result in a fatal error:
PHP Fatal error: Call to undefined function square_it()
<?php
$code
= 'echo square_it(55);' ;
eval(
$code );?>
This will work
<?php
$code
= 'echo call_user_func('square_it', 55);' ;
eval(
$code );?>
Patanjali ¶
1 year ago
eval() is useful for preprocessing css (and js) with php to embed directly into a style tag in the head tag (or script tag at the bottom of body tag) of the HTML of the page.
This:
a. Prevents Flash of White in Chrome or Firefox (where an external css file arrives briefly too late to render the HTML).
b. Allows radical minifying by testing the page source to see if whole blocks of rules or code are even required, such as for tables.
c. Allows custom source-content-dependent css rules to be created on the fly. (I use this to create rules for positioned labels over an image that scale with it)
d. Allows generation of a hash of the processed css or js for use in the page's CSP header for style-src or script-src to prevent injection attacks.
Here eval() is safe because it is not using user-supplied (person or browser) information
Where is the problem in my eval code???
because Apache said:
Parse error: syntax error, unexpected
T_STRING in
E:xampphtdocs1phpmas_resincmysql_class.php(120)
: eval()’d code on line 1
my code:
$type1 = "row";
$query1 = mysql_query("SELECT * FROM table");
$textToEval = "mysql_fetch_{$type1}($query1);";
$query = eval($textToEval);
And what is the correct mode??
Thanks ..
asked Feb 1, 2011 at 19:04
1
Don’t use eval! Use PHP’s variable functions:
$function = 'mysql_fetch_' . $type1;
$query = $function($query1);
Oh, and if you want to know, what was the fault: You forgot to escape the $
in $query1
. It should be $query1
.
answered Feb 1, 2011 at 19:08
NikiCNikiC
101k37 gold badges190 silver badges225 bronze badges
1
-
#1
php синтаксис
[Wed Oct 3 01:44:12 2007] [error] PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1
вот сам файл
PHP:
if (!defined("IN_MKP")) {
die ("Sorry !! You cannot access this file directly.");
}
function mkportal_board_out() {
global $db, $userdata, $Checkmkout, $mkportals, $DB, $Skin, $MK_PATH, $MK_TEMPLATE, $mklib, $ForumOut, $mklib_board, $board_config;
$MK_PATH = "../";
require $MK_PATH."mkportal/conf_mk.php";
$mkportals->base_url = $MK_PATH.$FORUM_PATH."/index.php";
$mkportals->forum_url = $MK_PATH.$FORUM_PATH;
require_once $MK_PATH."mkportal/include/mk_mySQL.php";
$DB = new db_driver;
$DB->db_connect_id = $db->db_connect_id;
// assign member information
$mkportals->member['id'] = $userdata['user_id'];
$mkportals->member['name'] = $userdata['username'];
if($userdata['user_id'] == -1) {
$mkportals->member['id'] = "";
}
$mkportals->member['last_visit'] = $userdata['user_lastvisit'];
$mkportals->member['session_id'] = $userdata['session_id'];
$mkportals->member['user_new_privmsg'] = $userdata['user_unread_privmsg']."/".$userdata['user_new_privmsg'];
if ($userdata['user_last_privmsg'] > $userdata['user_lastvisit'] && $userdata['user_new_privmsg'] > 0) {
$mkportals->member['show_popup'] = 1;
}
$mkportals->member['email'] = $userdata['user_email'];
$mkportals->member['timezone'] = $userdata['user_timezone'];
//$mkportals->member['dateformat'] = $userdata['user_dateformat'];
//assign member group -> attention don't change this !!
$mkportals->member['mgroup'] = 3;
// assign to forum admin access to MKportal CPA
if($userdata['user_level'] == 1) {
$mkportals->member['g_access_cp'] = 1;
$mkportals->member['mgroup'] = 1;
}
if($userdata['user_id'] == -1) {
$mkportals->member['mgroup'] = 9;
}
if($userdata['user_level'] == 2) {
$mkportals->member['mgroup'] = 2;
}
$mkportals->member['theme'] = $userdata['user_style'];
if (empty($userdata['user_style'])) {
$mkportals->member['theme'] = $board_config['default_style'];
}
$mkportals->member['mk_lang'] = $userdata['user_lang'];
if (empty($mkportals->member['mk_lang'])) {
$mkportals->member['mk_lang'] = $board_config['default_lang'];
}
require_once $MK_PATH."mkportal/include/functions.php";
require_once $MK_PATH."mkportal/include/PHPBB/php_board_functions.php";
require_once "$mklib->template/tpl_main.php";
if($MK_OFFLINE && !$mkportals->member['g_access_cp'] && !$mklib->member['g_access_cpa']) {
$message = $mklib->lang['offline'];
$mklib->off_line_page($message);
exit;
}
ob_start();
eval($ForumOut); !!!!!!<== ВОТ ето 66 строка!!!!!!
$contentspage = ob_get_contents();
ob_end_clean();
$ForumOut = $mklib->printpage_forum("$mklib->forumcs", "$mklib->forumcd", "Forum", $ForumOut);
print $ForumOut;
}
Я подписал 66ю строку
Пишет мол синтаксическая ошибка, нимогу понять в чем суть
-
#2
PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1
ошибка в коде, который выполняется eval().
Mr_Max
Первый класс. Зимние каникулы ^_^
-
#3
PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1
[m]eval[/m]
-
#4
eval($ForumOut); !!!!!!<== ВОТ ето 66 строка!!!!!!
а что находится в переменной $ForumOut ?
-
#5
PHP:
$ForumOut .= ob_get_contents();
ob_end_clean();
} else {
eval($this->compiled_code[$handle]);
}
Mr_Max
Первый класс. Зимние каникулы ^_^
-
#6
echo $ForumOut;
Думаю без коментариев станет ясно.
-
#7
а теперь для тех кто в танке
-
#8
что тут непонятного?
ошибка синтаксиса — не в приведенном тобой коде, а в том коде, который eval’ится приведенным тобой кодом. Поэтому мы предлагаем тебе посмотреть на этот eval’юируемый код. Сделать это можно, распечатав значение переменной $ForumOut, в которой этот код лежит как строка.
Mr_Max
Первый класс. Зимние каникулы ^_^
-
#9
Mongolor
eval() evaluates the string given in code_str as PHP code.
То-есть грубо-говоря вставив в «чистый» скрипт значение переменной [m]$ForumOut[/m]
И выполнив этот скрипт Вы получите ответ всё ли в порядке с $ForumOut ну или где допущены ошибки.
$a = ‘echo «test passed»;’;
eval($a);
результат работы —
test passed
$a = ‘echo «test passed»‘;
eval($a);
результат работы —
Parse error: parse error, unexpected $, expecting ‘,’ or ‘;’ eval()’d code on line 1
Ищем глюк
echo $a —-> echo «test passed»
После вставки в «чистый» скрипт
<?php
echo «test passed»
die();
?>
Parse error: parse error, unexpected T_EXIT, expecting ‘,’ or ‘;’
Всё понятно?
По крайней мере мне лишь таким образом удалось отловить eval()’d глюки в одном из проектов.
-
#10
бррр.. Это не отладка, это ад просто… Не, правду мама говорила, что eval — это зло!
Mr_Max
Первый класс. Зимние каникулы ^_^
-
#13
boombick
Полностью согласен.
К сожалению, иногда такое в руки попадается.
-
#14
ярым примером может служить использование ENUM в Mysql. Других вариантов выцеживания пунктов этого типа я не нашел. Тjлько eval. Правда в других с этой ф-ией не сталкивался
-
#15
> ярым примером может служить использование ENUM в Mysql. Других вариантов выцеживания пунктов этого типа я не нашел. Тjлько eval.
Чего?
-
#16
Nogrogomed
причем тут это?
-
#17
hammet, в данной теме непричем. рызмышления на тему использования eval и не более того.
SiMM, приходилсь сталкиваться с проектами, использующими тип ENUM(‘Заказ принят к рассмотрению’, ‘Заказ выполнен’), и добавлять к ним третий элемент например ‘Заказ в обработке’. Так вот формировать <select> проще всего было с использованием eval, хотя по хорошему надо было бы создать еще одну таблицу.
-
#18
Nogrogomed а пример формирования селекта из енама, с помощью евал можно?
-~{}~ 04.10.07 16:51:
вообще, ещё есть alter table
-
#19
ALTER TABLE — это и так ясно. Но потом надо по любому переписывать код с выбором «текущего состояния» допустим с двух пунктов до трех.
На доделках чужих проектов чаще всего легче вставить «заплатку», чем переделывать структуру. Вот в качестве таких заплаток и используется примерно такой код:
PHP:
$sql = "DESCRIBE `zakaz` `status`";
$r = mysql_query($sql) or die(mysql_error());
$mas = mysql_fetch_assoc($r);
$Type = str_replace('enum', 'array', $mas['Type']);
$strEval = '$'.$mas['Field'].'='.$Type.';';
eval($strEval);
Хотя подобный подход нарушает нормализацию отношений по теории БД, но в условиях «надо побыстрее сделать» — помогает
П.С. В конце кода для проверки вставляем var_dump($$mas[‘Field’]);
-
#20
Не, правду мама говорила, что eval — это зло!
+1
во всех рекомендациях говорится — что это признак плохого тона.