POO PHP Function Insert into MYSQL

Asked

Viewed 1,252 times

1

Hello, I’m wanting to do a function to insert the data in the table, is not returning me anything, look at the code:

 function insertInto ($tabela, $colunas=array(), $valores=array()) {

            foreach ( $valores as $valor ){
                   $valor = implode(',', $valores);
                   return $valor;
    }

    foreach ($colunas as $coluna){
                $coluna = implode(',', $colunas);
                return $coluna;
    }

    $sql = "INSERT INTO $tabela ($coluna) VALUES ('$valor')";
            $handle = mysql_query($sql, $conexaobd) or die(mysql_error());

    if(!$this->query($sql, $coluna)->error()){
        return true;
    }

    return false;

}

this is the code of the data to insert in the table;

             if ($_POST['status_atual'] != $_POST['status']) 
                            {

                                $tabela = 'editais_status_historico';

                                $colunas = 'id_edital';
                                $colunas .= 'login_usuario';
                                $colunas .= 'data';
                                $colunas .= 'estado_anterior';
                                $colunas .= 'estado_novo';

                                $valores = $_POST['status'];
                                $valores .= $_POST['status_atual'];
                                $valores .= $_POST['idedital'];
                                $valores .= $_SESSION['user'];
                                $valores .= date("Y-m-d") . ' ' . date("H:i:s");


                                $status = $_POST['status'];
                                $status_atual = $_POST['status_atual'];

                                $id_edital = '0';
                                $id_usuario = $_SESSION['user'];

                                $data = date("Y-m-d") . ' ';
                                $data .= date("H:i:s");


                                insertInto($tabela, $colunas, $valores);

                            }
  • 2

    First the implode expects an Array as a second parameter, you even gave a default value of type array, but is concatenating everything as string ($colunas .=). Second of all, you’re wearing a return right after each foreach. What causes the function to return and not be run anymore. So your code basically runs the first foreach and goes back to who called the function. Try to enable error viewing in your PHP configuration which should also help you identify all errors.

  • 1

    Complementing @Pedrohenrique’s comment, it seems you don’t even need these foreachs, only the implode.

1 answer

2

In your case it would be something +/- like this:

if ($_POST['status_atual'] != $_POST['status'])
{
    //passe os dados pra um unico array.
    $dados = array(Coluna => valor
        id_edital => $_POST['status'],
        ....)
}

function insertInto ($tabela, $dados) {

    //use o foreach para ler os dados vindos do array e adicionalos a outro array
    foreach($dados as $key => $value){
                $campos[] = $key; // recebe as colunas
                $valores[] = $value; // recebe os valores das colunas
    }

    //com o implode ele montara a string SQL
    $sql = 'INSERT INTO '.$tabela.'(';
    $sql .= implode(', ' $campos).') VALUES ('. implode(', ', $valores).')';

    $handle = mysql_query($sql, $conexaobd) or die(mysql_error());

    if(!$this->query($sql, $coluna)->error()){
        return true;
    }

    return false;
    }

And an Example using the PDO:

public static function insert($tabela, $dados){
            $sql = 'INSERT INTO '.$tabela.' (';
            foreach($dados as $key => $value):
                $campos[] = $key;
                $tokens[] = '?';
                $valores[] = $value;
            endforeach;
            try{
                $sql .= implode(', ', $campos).') VALUES ('.implode(', ', $tokens).')';
                $query = self::$conexao->prepare($sql);
                $query->execute($valores);
            }catch(PDOException $e){
                self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
            }
        }

In the $dados you pass a Array with the data that will be inserted in the table. Ex:

array(  id_edital =>  valor,
        login_usuario =>  valor
     , ...
     )

You can take yours if ($_POST['status_atual'] != $_POST['status']) and play within a Array as an example above, transforming the columns into Key and the Values in Value. and pass it to the function Insert;

  • 1

    A valid and good example, using PDO with prepared statements (which is essential). But I think it’s a little too complex compared to the original question. Don’t get me wrong, I liked your answer. But I don’t believe that just putting an example of code solves the problem of our friend (since he doesn’t use PDO probably this code nor should it work without first making changes). Try to edit your question by explaining the logic a little better. =)

  • 1

    I edited the answer adding +/- as it should be in the case of him.

Browser other questions tagged

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