我编写了一个从表中调用数组的函数
function fetchoperator($operator_type)
{
global $mysqli;
$stmt = $mysqli->prepare("SELECT
id,
operator_name
FROM gb_operators WHERE operator_type = ?
");
$stmt->bind_param("s", $operator_type);
$stmt->execute();
$stmt->bind_result($id,$operator_name);
while ($stmt->fetch()){
$row = array('id' => $id, 'operator_name' => $operator_name);
}
$stmt->close();
if(!empty($row))
{
return ($row);
}
else
{
return "";
}
}
现在在主页
$oprtor=fetchoperator(1);
现在进入html页面
<select id="MPOperator" name="opr" class="form-control" required>
<?php foreach($oprtor as $v2) {
echo "<option value=".$v2['id'].">".$v2['operator_name']."</option>"; } ?>
</select>
现在当我在没有foreach()函数的情况下使用时,我得到了表的最后一行的值,但是当我使用foreach函数时,我得到一个输出为V
但它应该显示14列。请帮我解决错误!!!!
答案 0 :(得分:0)
您正在覆盖$row
变量。这就是为什么你只获得最后一行。将其转换为$row[]
,将行推入$row
数组。
这样做
while ($stmt->fetch()){
$row[] = array('id' => $id, 'operator_name' => $operator_name);
}
答案 1 :(得分:0)
你没有填充一个数组,你已经多次写一个标量变量了
function fetchoperator($operator_type)
{
global $mysqli;
$stmt = $mysqli->prepare("SELECT id, operator_name
FROM gb_operators
WHERE operator_type = ?
");
$stmt->bind_param("s", $operator_type);
$stmt->execute();
$stmt->bind_result($id,$operator_name);
while ($stmt->fetch()){
// error here
//$row = array('id' => $id, 'operator_name' => $operator_name);
$row[] = array('id' => $id, 'operator_name' => $operator_name);
}
$stmt->close();
if(!empty($row)) {
return $row;
} else {
return "";
}
}
答案 2 :(得分:0)
使用array_push()在数组中添加新值。在你的情况下。你只需要为数组设置一个新值。
constructor (){
super();
this.state = {
sortType: 'top' //default is to sort by Top
};
this.setSortType = this.setSortType.bind(this);
}
componentWillMount(){
//this retrieves sourceName which is required to make the API call
const parsed = queryString.parse(this.props.location.search);
var sourceName = parsed.sourceId;
//getArticles below is the action that makes the API call with sourcename and sortType as parameters
newsActions.getArticles(sourceName,this.state.sortType);
newsStore.on('articles_change',this.fetchNewsArticles);
}
//Call to setState when user clicks button change sort parameter
setSortType(){
this.setState({
sortType:'latest'
});
}
render() {
return (
<div>
... //logic to display data from the API call
<button onClick={this.setSortType}> Sort By Latest </button>
</div>
);
}