Cómo agregar el símbolo `para esta consulta

Aquí está el código de ejemplo:

<?php

function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
if (($handle = fopen($source_file, "r")) !== FALSE) {
    $columns = fgetcsv($handle, $max_line_length, ",");
    foreach ($columns as &$column) {
        $column = str_replace(".","",$column);
    }
    while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
        while(count($data) < count($columns)) {
            array_push($data, NULL);
        }
        $c = count($data);
        for($i = 0; $i < $c; $i++) {
            $data[$i] = "'{$data[$i]}'";
        }
        $sql[] = '(' . implode(',',$data) . ')';
    }
    $query = "INSERT INTO $target_table (".implode(",",$columns).")VALUES " . implode(',',$sql) . "\n";
    echo $query;
    fclose($handle);
     }
 } 

 $file = 'test.csv';
 $table = 'test';

 csv_file_to_mysql_table($file,$table);

?>

So now it will echo : INSERT INTO Mytable (FirstName,LastName) VALUES ('A','B').I put echo instead of mysql_query($query) because I just want to see how is the query.

I tried to add ` for each of my column name , but get error.

Can I get some hints how to add it?

preguntado el 08 de noviembre de 11 a las 19:11

2 Respuestas

You could use array_map with a comma join to do this:

  $columns = join(",", array_map(
                function($col) { return "`".$col."`";}, 
                array_values($columns)));

You could also use this to make doing the values a little easier too:

  $values = join(",", array_map(
                function($val) { return "'".$val."'";}, 
                array_values($values)));

I use these a lot when I have an array structure like:

array('FirstName' => 'A', 'LastName => 'B');

Then I can just do this (using PDO and prepared statements):

                $posted = array('FirstName' => 'A', 'LastName => 'B');

                $columns = join(",", array_map(
                function($col) { return "`".$col."`";}, 
                array_keys($posted)));

                $namedparams = join(",", array_map(
                function($col) { return ":".$col;},
                array_keys($posted)));


                $query = "INSERT INTO `sometable` ({$columns}) VALUES ({$namedparams})";

                $stmt = $db->prepare($query);   
                $stmt->execute($posted);

Which will ensure my data is put in safely, matching the named paramaters to the $posted array.

Note: This does require 5.3, but you can just take out the inline functions, and make them real functions for earlier php versions.

me gusta:

echo join(",", array_map('colize', array_values($posted)));

function colize($col){return "`".$col."`";}

respondido 09 nov., 11:00

It does? I'm assuming you meant to use . instead of + as this is not java.... But I still can't get it to work: codepad.org/nd7gSWXo Tell me how this is supposed to work exactly the same please, I'd like to use it instead if it is shorter. - Ben

Corrección: the code should be as follows: "$columns = '`' . join('`, `', $columns) . '`';". Ver this codepad for a proof. My original posting indeed incorrectly concatenated, but I believe you know how to use it. The current version is still shorter and does exactly the same, además de is compatible with PHP less than 5.3. - Tadeck

I do not see the reason to create additional function only to concatenate, then use its result to concatenate and then... concatenate again. Instead of complicating the solution just a simple join() / implode() call is enough. - Tadeck

Thanks for updating your comment, that does work well and is definitely more simple. I will probably make use of this for simple things in the future; I learn something new here everyday! - Ben

What is the error you get? Can you show that, and the contents of the generated query (e.g. echo $sql).

A backtick (`) is only required for field or table names that are actually reserved words, e.g.

INSERT INTO `select` (`update`) VALUES (...)

However, note that your code is vulnerable to SQL injection. Even though the fieldnames/values are coming out of a CSV file, if any of those names/values contain a quote (') or other SQL metacharacter, your query will fail. You MUST pass them through mysql_real_escape_string() before inserting them into the SQL query string.

respondido 08 nov., 11:23

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.