How to pass an array in php’s Query function?

Asked

Viewed 599 times

4

Well, I need to spend two in the php query, but I can’t pass them otherwise:

$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 worked out, but I thought it was too much to do it this way, I believe there’s some better way to do it!

  • $columns and $Dates are the arrays that are coming in, their size is undefined, since I will pass this data in several places.

  • I put " ',' "as implode

  • 1

    I recommend using parameterized queries instead of playing the values this way, as it may be vulnerable to SQL Injection.

  • I think that ORM can help you in this case.

  • You can also use serialize: http://php.net/manual/en/function.serialize.php . But use prepare to prevent sql Injection

  • Is this Mysqli or PDO? Why can it make a difference

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 thus used

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

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

  • If I enter 5 data, this function will cause the 5 to be entered in the database?

  • Yes, with this function you can enter the data you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.