【问题标题】:Getting all values used in iterations after the loop finishes in PHP [duplicate]在PHP中循环完成后获取迭代中使用的所有值[重复]
【发布时间】:2015-03-20 14:28:54
【问题描述】:

我有以下代码:

$DB->newclient(array(
"a" => $_POST["a"],
"b" => $_POST["b"],
"c" => $_POST["c"]
));

function newclient($other = array()){
$keys = array_keys($other);
$columns = implode(",", $keys);
$colVals = implode(",:", $keys);
$sql = $this->dbh->prepare("INSERT INTO `clients` ($columns) VALUES(:$colVals)");
 foreach($other as $key => $value){
    $value = htmlspecialchars($value);
    $sql->bindValue(":$key", $value);
    echo $value;    // print all values
}
echo $value; // only print first value
$sql->execute();
return true;
}

我需要在循环之后获取所有值,但$value 只包含一个值。

你能帮帮我吗?

更新:

我只想将值插入列中,因此 sql->execute 不起作用,因为我无法获取所有值。 第一列是 id 和自动增量。 如果我调试 sql:

echo "INSERT INTO `clients` ($columns) VALUES($value)";
INSERT INTO `clients` (a,b,c) VALUES(a)

echo var_export($sql->errorInfo()); 
array (
0 => '',
1 => NULL,
2 => NULL,
3 => NULL,
)

为什么值是空的?

【问题讨论】:

  • echo $value; // only print first value 实际上会打印 last 值,因为您的循环只是一遍又一遍地覆盖$value。你真正想做什么?
  • 感谢您的回答。更新我的问题
  • 我发现了我的问题,我在我的数据库中遇到了一个错误,非常抱歉,非常感谢您的帮助

标签: php arrays


【解决方案1】:

$value 是一个标量字符串。它在每次迭代中都会被覆盖,因此您只能获得循环后的最后一个值。

您需要在每次迭代中创建一个数组并在数组中添加一个值:

$sql = $this->dbh->prepare("INSERT INTO `clients` ($columns) VALUES(:$colVals)");

$allValues = array(); // initialize an array for values

foreach($other as $key => $value){
   $value = htmlspecialchars($value);
   $sql->bindValue(":$key", $value);
   $allValues[] = $value; // store current value in array
}

var_dump($allValues); // print all values. 
// You may use `print_r` instead of `var_dump`, or whatever

此外,您可以使用array_values() 函数从数组中获取所有值,而无需任何循环:

$allValues = array_values($other);
var_dump($allValues); 

【讨论】:

  • 谢谢!你的回答是对的,我现在可以获取所有值,但是当我执行查询时,无法获取所有值...更新我的问题
  • 我发现了我的问题,我在我的数据库中遇到了一个错误,非常抱歉,非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 2020-12-16
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 2020-05-01
相关资源
最近更新 更多