php - 通过PHP解析字典对象并创建MySQL表

标签 php mysql parsing dictionary

目前,我的 PHP 脚本中有这个字典对象,该对象通过我的 iOS 应用程序发布到我的 PHP 实现的服务器:

{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}

现在我需要根据数据创建一个 MySQL 表...

这是我尝试解析数据,但我得到的只是对象,而不是键......

foreach( $text as $stuff ) {
    if( is_array( $stuff ) ) {
        echo json_encode($stuff);
        foreach( $stuff as $thing ) {
            echo json_encode($thing);
        }
    } else {
        echo json_encode($stuff);
    }
}

结果如下...“保存”“GameScore”“0”“SeanPlott”“1337”

这就是我计划进行的查询

$result = query("INSERT INTO '%s'('%s', '%s', '%s', '%s') 
                    VALUES('%s','%s','%s','%s')", $classname, $key1, $key2, $key3, $key4, 
                                                    $object1, $object2, $$object3, $object4);

但是查询应该是动态的,因为字典对象可以有 1 个或多个键/对象...

所以我想我需要实现一个解析 for 循环,在数组中生成查询并输出一个字符串,该字符串是查询...

有人对如何修复我的解析器有任何想法吗?

编辑:这是我处理 MYSQL 的查询函数

function query() {
    global $link;
    $debug = false; 
    $args = func_get_args();
    $sql = array_shift($args);

    for ($i = 0; $i < count($args); $i++) {
        $args[$i] = urldecode($args[$i]);
        $args[$i] = mysqli_real_escape_string($link, $args[$i]);
    }

    $sql = vsprintf($sql, $args);

    if ($debug) print $sql;

    $result = mysqli_query($link, $sql);

    if (mysqli_errno($link) == 0 && $result) {  
        $rows = array();

        if ($result !== true)
            while ($d = mysqli_fetch_assoc($result)) 
                array_push($rows,$d);

        return array('result' => $rows);

    } else {
        return array('error' => 'Database error');
    }
}

编辑:花了我一段时间和很多帮助,但我完成了它...它会处理值中空格的情况,并在相应的值包含空格时在键周围添加“`”字符...

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"Sean Plott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_slice(array_keys($data), 2);
array_shift($data);
$table_title = array_shift($data);

$values = array();
$num = 0;
foreach($data as $key => $value) {
    if(strpos($value, " ") !== false) $columns[$num] = "`".$columns[$num]."`";
    $num = $num + 1;
    $values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}

$final_statement = "INSERT INTO " . $table_title . " (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;

如果有人看到任何方法可以优化它或使其更干净......请随时发布内容!

再次感谢大家的意见!

最佳答案

您可以使用简单的 json_decode()implode() 来格式化它并准备插入。考虑这个例子:

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns

$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES ('".implode("','", $data)."')";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save','GameScore','0','SeanPlott','1337')

编辑:假设您的列具有 int 类型(尤其是具有数值的列)。不管出于什么原因它不起作用,因为不匹配,如果是这样,你可能会这样做。考虑这个例子:

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns

$values = array();
foreach($data as $key => $value) {
    // if not numeric, add quotes, if not, leave it as it is
    $values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}

$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save', 'GameScore', 0, 'SeanPlott', 1337)
// Note: numbers has no qoutes

关于php - 通过PHP解析字典对象并创建MySQL表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879707/

相关文章:

PHP 脚本在准备好的语句中的 execute() 处停止执行

c++ - 以编程方式解析和编辑 C++ 源文件

python - 无法使用 pyparsing 正确解析此文件

parsing - REXX - 从 CSV 文件解析

mysql - 使用以相同字段开头的 GROUP BY 优化多个查询

php - MYSQL/PHP - 如何制作 "Sort By"下拉列表以对从 mysql 提取的结果进行排序

php - 以阿拉伯语显示日期

php - PHP 中的 "$this"是什么?

php - 如何在 PHP 中构建多维数组

php - Grammar::parameterize() 必须是数组类型