PHP 准备语句连接:来自 while 循环的 "comma"、"and" 和 "period"

PHP prepared statement concatenate: "comma", "and", and "period" from while loop

我正在尝试从 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>";

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

如您所料,您的问题代码就是您标记的部分。

//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);

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