【问题标题】:PHP prepared statement concatenate: "comma", "and", and "period" from while loopPHP 准备好的语句连接:while 循环中的“逗号”、“与”和“句点”
【发布时间】:2015-11-22 19:26:40
【问题描述】:

我正在尝试从 MySQL 查询构建一个句子。我相信我的连接部分正在工作,因为我已经替换了一个静态数组。可能有人会引导我朝着正确的方向了解我的 while 循环会生成所需的数组吗?如何从我的 mysql 语句创建关联数组?

$query = "SELECT name, dob FROM children WHERE personal_id = ?";
$statement = $db->prepare($query);
$statement->bind_param('i', $_SESSION['mysqlID']);
$statement->bind_result($name, $dob);
$statement->execute();

// Store the results
$statement->store_result();

// Get the number of rows
$num_of_rows = $statement->num_rows;


**//I believe my problem lies in this array ?**
$m_children = [];
while ($statement->fetch()) {
  $m_children[] =  $name;
  $m_children[] .=  $dob;
}

$num_children = intval($num_of_rows);
$children = [];

foreach ($m_children as $k => $v) {
  $dob = strtotime($dob[$k]);
  $children[] = "$v, born on {$dob}";
}

$tmp = array_pop($children);

  if ($num_children > 1) {
    $children_type = 'children';
    $children = join(', ', $children) . ' and ' . $tmp;
  } else {
    $children_type = 'child';
    $children = $tmp;
  }

$children = "<p>I have the following ". $children_type .": ". $children .".</p>";

【问题讨论】:

  • 如何从我的 mysql 语句创建关联数组?
  • 所需输出的示例?
  • 谢谢。数据库正在返回姓名和出生日期。我需要阅读这个句子。 “名”生于“日”,“名”生于“日”,“名”生于“日”。如果一个结果只是以句号结尾。
  • 这段代码到处都是。。$statement2 和 foreach 中的 $dob 数组甚至来自哪里?

标签: php arrays prepared-statement concatenation


【解决方案1】:

总体而言,您的代码看起来还不错。语法部分肯定是可靠的(弹出最后一个元素,用逗号等连接其余元素......)

正如您所怀疑的,您的问题代码就是您标记的那部分。

//I believe my problem lies in this array ?
$m_children = [];
while ($statement2->fetch()) {
  $m_children[] =  $name;
  $m_children[] .=  $dob;
}

$num_children = intval($num_of_rows);
$children = [];

foreach ($m_children as $k => $v) {
  $dob = strtotime($dob[$k]);
  $children[] = "$v, born on {$dob}";
}

这是一个改进建议:

$children = [];
while( $statement2->fetch()) {
    $children[] = $name." born on ".date("d/M/Y",strtotime($dob));
}
$num_children = count($children);

无需对数据进行两次传递,您需要格式化出生日期(否则您只会获得时间戳)。然后这段代码可以继续你的语法格式,这对我来说似乎很好。

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 2010-10-05
    • 2018-08-29
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多