1

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;`
1
  • 1
    use implode(',', array_keys($arrayDados)) for columns and implode("','", array_values($arrayDados)) for values Commented Oct 6, 2012 at 4:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Docs: array_keys - array_values - implode

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.