【问题标题】:convert string to variable within prepared statement在准备好的语句中将字符串转换为变量
【发布时间】:2015-10-23 02:51:57
【问题描述】:

我正在创建一个将 csv 文件导入现有 mySQL 数据库的 php 脚本。

我通过检查标题是否在数组中来选择匹配的列标题并尝试使用列号将我的输入创建到我准备好的语句中。

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$numCols = count($data);
$row     = array();

// process the first row to select columns for extraction
if($isFirstRow) {
        $num = count($data);
        for($col=0; $col<count($columns); $col++){
            for($c=0; $c<$numCols; $c++)

                if(!in_array($data[$c], $columns[$col])){
                    if($c == ($numCols-1))
                        {
                            $matchingCol[$col] = '""';
                        }
                    }
                    else{
                        $matchingCol[$col] = 'data['.$c.']';
                         apc_store("foo$c", $matchingCol[$col]);
                }

        }

    $isFirstRow = false;
}

$data = array(
'contractorName' => (apc_fetch('foo1')) ,
'contractorType' => $matchingCol[3]); 
$query = "INSERT INTO uploadSQL SET" . bindFields($data);

$result = $pdo->prepare($query); 
$result->execute($data);

发布到数据库的数据是'$data[3]''$data[5]'等。 如何让 INSERT 输入存储在 $data[3] 而不是字符串 '$data[3]' 的数据?

【问题讨论】:

  • 使用$data[$c] 而不是'data['.$c.']'...!?
  • @deceze 请将您的答案发布为答案而不是 cmets。由于 cmets 经常被忽略,因此其他人很难找到答案。
  • @Harish 如果我认为答案是值得的,我相信这是答案。这更像是在黑暗中拍摄,因为尽管代码太多,但问题相当模糊。

标签: php mysql csv upload


【解决方案1】:
Use $data[$c] instead of 'data['.$c.']'...!?

单引号字符串将几乎完全“按原样”显示内容。不会解释变量和大多数转义序列。

【讨论】:

  • @deceze 如果我使用 $data[$c] 而不是 'data['.$c.']' 它会从第一行获取字符串,即列标题并将其插入每个数据库中的行。
【解决方案2】:

不是问题的确切解决方案,而是解决方法。我确信有更有效的方法。

 if($isFirstRow) {
        $csvRow1 = $data;
    }
                            $num = count($data);


            for($col=0; $col<count($columns); $col++){
                for($c=0; $c<$numCols; $c++){

                    if(!in_array($csvRow1[$c], $columns[$col])){
                                                if($c == ($numCols-1))
                        {
                            $matchingCol[$col] = '""';
                        }
                    }
                    else{

                            $matchingCol[$col] = "$data[$c]";
                            $c = $numCols;
                    }
                }
            }

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多