-3

I have an array of variables:

$values = array($a,$b,$c);

i want to pass this array through this function:

function db_insert($table, $attributes, $values)//insert into the database
{
    // $values and takes an array of variables. $attributes is a string  "att1, att2,...."
    $result = mysql_query("INSERT INTO ' '".$table."' ( '".$attributes."' ) VALUES ( '".implode("','", $values)."' )");    
    return $result;
}

I pass it like this but it doesn't work:

db_insert("table","a,b,c",$values);

There is no errors but the record is not stored into the database. What is the problem?

onlyforthis
  • 444
  • 1
  • 5
  • 21
  • If you echo `"INSERT INTO ' '".$table."' ( '".$attributes."' ) VALUES ( '".implode("','", $values)."' )"` and execute it manually on the db does it work? – chris85 Mar 01 '15 at 17:51
  • Yes i tried that. It works – onlyforthis Mar 01 '15 at 17:53
  • Have you tried this as well? `if (!$result) { die('Invalid query: ' . mysql_error()); }` – chris85 Mar 01 '15 at 17:57
  • `"INSERT INTO ' '".$table."'` Besides a spurious `'` anyway; don't wrap a table name in `'`.... if you wrap it, wrap it in backticks (`\``).... likewise for column names (attributes) – Mark Baker Mar 01 '15 at 17:59
  • 1
    @hzjw - if you had echoed the sql query, and tried to execute it manually on the database, it would have errored – Mark Baker Mar 01 '15 at 18:09

1 Answers1

1

You probably want this:

$result = mysql_query("INSERT INTO $table ($attributes) VALUES ('".implode("','", $values)."')");

As a side note you should switch to using mysqli_ functions or PDO instead of mysql_, see why here. You should also read a bit on placeholders and how to use them in your queries.

Community
  • 1
  • 1
mhall
  • 3,671
  • 3
  • 23
  • 35