如何在while循环中添加多个值,我只能根据我的级别添加两个值,一个是id,另一个是title,我想添加更多字段,比如我从服务器获取请帮助任何人
$limitStart = $_POST['limitStart'];
$limitCount = 15;
if(isset($limitStart) || !empty($limitstart)) {
$con = mysqli_connect($hostname, $username, $password, $dbname);
$query = 'SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit '.$limitStart.','.$limitCount .'';
$result = mysqli_query($con, $query);
$res = array();
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['featured_image'];
}
echo json_encode($res);
}
答案 0 :(得分:0)
只需将它们全部添加,因为$resultSet
已经是一个关联数组:
while ($resultSet = mysqli_fetch_assoc($result)) {
$id = $resultSet['id'];
unset($resultSet['id']); // <-- add this is if you don't want the id in the final set as it's now the key.
$res[$id] = $resultSet;
}
或者选择某些字段,只需做一些基本的PHP,将additinonal字段添加为新的关联数组。
以下是添加caption
和featured_image
的示例:
while ($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = ['featured_image'=>$resultSet['featured_image'],
'caption' => $resultSet['caption']];
}
答案 1 :(得分:0)
可能是这样的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Converters.Add(new BsonDocumentJsonConverter());
}
}
会做到这一点吗?
答案 2 :(得分:0)
如果$ limitStart为14且$ limitCount为15,则应返回一个id。
$limitStart = $_POST['limitStart']; // What is this number?
$limitCount = 15;
你的if语句中有一个拼写错误,见下文。
此外,您的代码易受SQL注入攻击,因为您没有准备好您的语句。
if( isset( $limitStart ) || !empty( $limitStart ) ) { // Typo here. (small s)
$mysqli = mysqli_connect($hostname, $username, $password, $dbname);
$sql = "SELECT id, title, caption, description, featured_image, logo, category_sku, industry_sku
FROM works ORDER BY title limit ".$limitStart.",".$limitCount."";
$stmt = $mysqli->prepare($sql); // Prepare the statement
$stmt->bind_param("ii", $limitStart, $limitCount); // Bind the parameters
$stmt->execute(); // Execute the query
// Bind the result
$stmt->bind_result($id, $title, $caption, $description, $featured_image, $logo, $category_sku, $industry_sku);
$result = $stmt->get_result();
$res = array();
while ($resultSet = $result->fetch_assoc()) {
$res[$resultSet['id']] = $id;
}
$stmt->close(); // Close the statement
$mysqli->close();
echo json_encode($res);
}