treehouse : what would you like to learn today?
Web Design Web Development iOS Development

php mysql functions

  • 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['table'];
    $j = 0;
    foreach($values['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?
  • 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['table'] . " (" . join(', ', array_keys($data['values'])) . ") VALUES ('" . join("', '", array_values($data['values'])) . "')";

    if (!mysql_query($sql)) {
    die('MySQL Error: ' . mysql_error());
    }
    } else {
    die('Invalid argument given, must be an array!');
    }
    }
  • This is a pretty standard feature of most frameworks. I'm currently in the process of doing the same, although with prepared statements. Learning a lot of new things about dynamic prepared statements as well!

    As @SgtLegend says, you can do things much quicker with array_keys() and array_values()