【问题标题】:How does implode() work with array of variablesimplode() 如何处理变量数组
【发布时间】:2015-03-01 17:48:33
【问题描述】:

我有一个变量数组:

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

我想通过这个函数传递这个数组:

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;
}

我是这样通过的,但它不起作用:

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

没有错误,但记录没有存储到数据库中。有什么问题?

【问题讨论】:

  • 如果你回显"INSERT INTO ' '".$table."' ( '".$attributes."' ) VALUES ( '".implode("','", $values)."' )" 并在数据库上手动执行它是否有效?
  • 是的,我试过了。它有效
  • 你也试过这个吗? if (!$result) { die('Invalid query: ' . mysql_error()); }
  • "INSERT INTO ' '".$table."' 除了一个虚假的' 反正;不要在'....中包含表名
  • @hzjw - 如果你回显了 sql 查询,并尝试在数据库上手动执行它,它会出错

标签: php arrays variables implode


【解决方案1】:

你可能想要这个:

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

作为旁注,您应该改用 mysqli_ 函数或 PDO 而不是 mysql_see why here。您还应该阅读一些关于占位符以及如何在查询中使用它们的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2012-05-12
    • 2019-05-01
    • 2023-03-24
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多