During a foreach when incrementing the string duplicates a character at the end

Asked

Viewed 29 times

1

I am developing an api for personal use and mysqli management that makes the user not need many codes or phpMyAdmin (for website use etc). But I am trying to combine the INSERT INTO command with a function:

function Query($sqlcommand){
    return $this->mysqli_conexao($sqlcommand);
}

function InsertInto($table, $fields, $values){
    $sqlCommand = "INSERT INTO $table ";

    $sqlCommand .= "("

    $resultField;

    foreach($fields as $field){
        $resultField .= "'" . $field . "',";
    }

    $sqlCommand .= ") VALUES (";

    $resultValue;
    foreach($values as $value){
        $resultValue = "'" . $value . "',";
    }

    $sqlCommand .= ")";

    echo $sqlCommand;
}

But at the end always adds an extra quote and comma and causes error.

Ex gets like this: $miConnector->InsertInto('test', array('a','b'), array('letra a', 'letra b'));

INSERT INTO `test` ('a','b',') VALUES ('letra a', 'letra b',')

Complete code: Miconnectorapi

I solved this way without the foreach and did not fail:

$sqlcommand = "INSERT INTO " . $table . " (`" . join($fields, '`,`') . "`) VALUES ('" . join($values, '\',\'') . "')";
  • I found it! I used it http://pastebin.com/StHpU1Gc

  • You could also use the implode, a little cleaner than yours: http://ideone.com/Zq1k0S

  • 1

    Yes but this code will not stay the sample :) is just a mysqli api/bridge that I am developing, but thanks for the tip

  • @zekk reviewing the implode really its code was very clean and I will use in another api.

No answers

Browser other questions tagged

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