Renato
Renato

Reputation: 345

how to convert array into variables in php

I want to create a function that takes the name of a table and an array with the column name and value to use it to generate an INSERT in MySQL

Check my code.

Unfortunately this technique does not work as it always generates a comma after each value and this generates an error when entering data. Anyone know a better way to create this function?

<?php
$arrayDados = array('nome' => 'Renato', 'idade' => 24, 'peso' => 36, 'mae' => 'neide');
$colunas = "";
$valores = "";
$tabela = 'cadastro';

    foreach ($arrayDados as $key => $value) {
        $colunas .=  $key . ', ';
        $valores .= $value.', ';
    }
$sql = "INSERT INTO $tabela ($colunas) VALUES ($valores)";

echo $sql;`

Upvotes: 1

Views: 1490

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

$sql = "INSERT INTO $tabela (".implode(",",array_keys($arrayDados)).") VALUES (".implode(",",array_values($arrayDados)).")";

Docs: array_keys - array_values - implode

Upvotes: 1

Brad
Brad

Reputation: 163232

Take a look at implode(): http://php.net/manual/en/function.implode.php

implode(',', $yourArray);

Really though, use prepared queries instead of stuff like this where possible, to avoid problems with unescaped data.

Upvotes: 2

Related Questions