How to pass an array in the php Query function?

4

Well, I need to pass two in the php query, but I can not pass them without being as follows:

$coluna = implode( ',' , $colunas);

$date = implode( " ',' " , $dates);

$teste2 = "'$date'";

//O teste2 está gerando algo como: 'exemplo', 'exemplo'

$sql = "INSERT INTO $table ($coluna)

VALUES ($teste2)";

  if ($conn->query($sql) === TRUE) {

      echo "<br>Dados enviados com sucesso!";

  }

  else {

    echo '<br>Não foi possível enviar os dados!';

  }

The way it works out, but I thought it was a lot of gambiarra to do that, I think there is some better way to do it!

  • $ columns and $ dates are the arrays that are arriving, their size is undefined, since I will be passing those data in several places.

  • I put "','" as implode

asked by anonymous 21.08.2017 / 00:33

1 answer

1

You can use this function is simpler.

function insertBD($array, $tbName){
        $variavel_insert_colunas = "";
        $variavel_insert_valores = "";
        $count = count($array)-1;
        $i = 0;
        foreach ($array as $key => $value) {
            if($i < $count){
                $virgula = ",";
            }else{
                $virgula = "";
            }
            $variavel_insert_colunas .= $key.$virgula." ";
            $variavel_insert_valores .= "'".$value."'".$virgula." ";
            $i++;
        }
        $sql = "INSERT INTO ".$tbName." (".$variavel_insert_colunas.") VALUES (".$variavel_insert_valores.")";

        return $sql;
    }

The function is used as well

$array = array('nome' => $_POST["nome"], 'texto' => $_POST["texto"]);
$result = $conn->query(insertBD($array, "comentario"));

In the function insertBD the 1st parameter is the array with the columns and with the data the 2nd parameter is the name of the table.

    
31.10.2017 / 12:04