仅从MYSQL更新语句中选择列名的函数

时间:2016-02-11 10:55:18

标签: php mysql

我有一个字符串(MYSQL更新语句): $string = "UPDATE myTable SET grade=99.9, name='moe', city='Taiz',pass_id=0202 where ID=99";

我想要一个PHP函数来帮助我获取列名,以便字符串变为: $columns = "grade,name,city,pass_id";

我尝试使用此代码,但没有像预期的那样工作:

 $beginningPos = strpos($string, '=');
    $endPos = strpos($string, ',');

    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

    return str_replace($textToDelete, '', $string);

1 个答案:

答案 0 :(得分:1)

试试这个脚本

//use strtolower($string) if needed
$string = "UPDATE myTable SET grade=99.9, name='moe', city='Taiz',pass_id=0202 where ID=99"; 

        if ( strpos($string, 'where') !== false){
            $string = explode('where', $string);
            unset($string[1]); 
        }

        $exp = explode('=', $string[0]);
        $columns = ''; 
        foreach ( $exp as $e ) {
            $res = str_replace(',', ' ', $e);
            $res = explode(' ', $res); 
            $res = array_pop($res); 
            if ( $res)
                $columns .= $res .','; 
        }
        $columns = rtrim($columns, ','); 

<强>输出

string(23) "grade,name,city,pass_id"