Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End php mysql functions

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #34789
    marcdefiant
    Participant

    Hey guys, I was making some functions for easier database input and updating. This is one of them.

    function mysql_insert($values){
    if(is_array($values)){
    $table = $values;
    $j = 0;
    foreach($values as $key => $val){
    $keys[$j] = $key;
    $vals[$j] = '''.$val.''';
    $j++;
    }
    $values = implode(', ', $vals);
    $keys = implode(', ', $keys);
    mysql_query("INSERT INTO $table ($keys) VALUES ($values);") or die(mysql_error());
    }else{
    // Error if $values is not an array
    }
    }

    This would be the use:

    $values = array(
    'table' => 'posts',
    'values' => array(
    'title' => $title,
    'slug' => $slug,
    'content' => $content,
    'author' => $author
    )
    );
    mysql_insert($values);

    Is this bad practice? or is there a better way I could/should be doing this?

    #89126
    SgtLegend
    Member

    While what you have above works it’s very cluttered with un-needed code, please see the below code for how you can do it with join(), array_keys() and array_values().

    function mysql_insert($data) {
    if (is_array($data)) {
    $sql = "INSERT INTO " . $data . " (" . join(', ', array_keys($data)) . ") VALUES ('" . join("', '", array_values($data)) . "')";

    if (!mysql_query($sql)) {
    die('MySQL Error: ' . mysql_error());
    }
    } else {
    die('Invalid argument given, must be an array!');
    }
    }
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.