【发布时间】:2015-03-22 03:53:14
【问题描述】:
如何解决 foreach mysql PDO 中的冲突 我尝试使用其他循环函数但没有给出结果,比如 while.this 我的脚本
mysql PDO 查询,如下所示:
<?php
function calldata($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
while($res = $q->fetch(PDO::FETCH_ASSOC)){
$record = array_map('stripslashes', $res);
$db->records[] = $record;
}
return $db->records;;
//else echo "No records found";
}
?>
并显示结果,如下所示:
<table>
<tr><td>Category</td><td>
<select>
<option value="0">- select -</option>
<?php
try{
$db = dbConn::getConnection();
$table='str_prod_category';
$recordscat = calldata($table);
if(count($recordscat)){
foreach($recordscat as $key1=>$Recordcat){
?>
<option value="<?=$Recordcat['id_category'];?>"><?=$Recordcat['cat_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
<tr><td>Brand</td><td>
<select>
<option value="0">- Select -</option>
<?php try{
$db = dbConn::getConnection();
$table1='str_prod_brand';
$recordsbrand = calldata($table1);
if(count($recordsbrand)){
foreach($recordsbrand as $key2=>$Recordbrand){
?>
<option value="<?=$Recordbrand['id_brand'];?>"><?=$Recordbrand['brand_name'];?></option>
<?php }}}catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error " . $e->getMessage();
} ?>
</select>
</td></tr>
</table>
此代码有效,显示数据,但对于选项选择品牌,有一个空选择,然后是空数据后的正确数据。
如何解决这个问题?我尝试将循环从 foreach 更改为 while,但没有给出结果。
谢谢
【问题讨论】:
-
mysql_error()不属于那里。并且您声明的方法名称是calldata(),但在演示文稿中使用getRecords()。 -
哦,对不起,我想念那个,实际代码是“calldata()”我编辑问题。