douhu2131 2016-01-25 14:08
浏览 52
已采纳

PHP,mysql - 在json_encode中使用for循环获取数据库表中的数据

sorry if my question-title is confusing..i don't know exactly how to put it. but here's what:

so..im trying to get the data in my database, put it in

<select><option>

tag. and echo it.

addtocart.php this is my first code and this is working fine, with preset values

<?php
define('INCLUDE_CHECK',1);
require "../connectDB.php";

if(!$_POST['img']) die("There is no such product!");

$img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM rooms_addons WHERE img='".$img."'"));

echo json_encode(array(
    'status' => 1,
    'id' => $row['id'],
    'price' => (float)$row['price'],
    'txt' => '<table width="65%" id="table_'.$row['id'].'">
  <tr>
    <td width="5%" style="display:none;"><input type="text" name="id[]" value="'.$row['id'].'" style="width: 28px; border-width: 0px;"></td>
    <td width="35%"><input type="text" name="roomname[]" value="'.$row['name'].'" style="width: 95px; border-width: 0px;"></td>
    <td width="20%">Php <input type="text" name="price[]" value="'.$row['price'].'" style="width: 40px; border-width: 0px;"></td>
    <td width="15%"><select name="qty[]" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');" style="width: 40px;">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option></select>

    </td>
    <td width="15%"><a href="#" onclick="window.remove('.$row['id'].');return false;" class="remove">remove</a></td>
  </tr>
</table>'
));
?>

now my problem is that, like what i've said, i want to put the "quantity" numbers (which is in my database table) in the

<select><option>

..with that here's what i've done:

<?php
define('INCLUDE_CHECK',1);
require "../connectDB.php";

if(!$_POST['img']) die("There is no such product!");

$img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM rooms_addons WHERE img='".$img."'"));

echo json_encode(array(
    'status' => 1,
    'id' => $row['id'],
    'price' => (float)$row['price'],
    'txt' => '<table width="65%" id="table_'.$row['id'].'">
  <tr>
    <td width="5%" style="display:none;"><input type="text" name="id[]" value="'.$row['id'].'" style="width: 28px; border-width: 0px;"></td>
    <td width="35%"><input type="text" name="roomname[]" value="'.$row['name'].'" style="width: 95px; border-width: 0px;"></td>
    <td width="20%">Php <input type="text" name="price[]" value="'.$row['price'].'" style="width: 40px; border-width: 0px;"></td>
    <td width="15%">
        $qty = $row["qty"];
        <select name="'.$row['id'].'_cnt" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');">
        for ($i=0;$i<=$qty;$i++) {
        <option>' . $i . '</option>
        }
        </select>
    </td>
    <td width="15%"><a href="#" onclick="window.remove('.$row['id'].');return false;" class="remove">remove</a></td>
  </tr>
</table>'
));
?>

my for-loop alone works well, but when i put that in echo json_encode, in addtocart.php the whole addtocart.php doesnt work.

i used the for-loop for select-option coz it is for quantity to be displayed in dropdown, like if whats in the database is 5 then it would appear as 1 2 3 4 5 in dropdown.

i don't know how to fix my code and i can't think of any other thing to replace the dropdown for selecting quantity of products/item with regards to my database data :( any suggestions? ..thanks in advance

  • 写回答

1条回答 默认 最新

  • dqe55175 2016-01-25 14:23
    关注

    Your problem is that you are attempting to use a loop within string concatenation, which is not possible. You can get around that by using implode and range instead to generate the same string:

    echo json_encode(array(
        'status' => 1,
        'id' => $row['id'],
        'price' => (float)$row['price'],
        'txt' => 
            '<table width="65%" id="table_'.$row['id'].'">
              <tr>
                <td width="5%" style="display:none;"><input type="text" name="id[]" value="'.$row['id'].'" style="width: 28px; border-width: 0px;"></td>
                <td width="35%"><input type="text" name="roomname[]" value="'.$row['name'].'" style="width: 95px; border-width: 0px;"></td>
                <td width="20%">Php <input type="text" name="price[]" value="'.$row['price'].'" style="width: 40px; border-width: 0px;"></td>
                <td width="15%">
                    <select name="'.$row['id'].'_cnt" id="'.$row['id'].'_cnt" onchange="change('.$row['id'].');">
                    <option>' . implode('</option><option>', range(0, $row["qty"])). '</option>
                    </select>
                </td>
                <td width="15%"><a href="#" onclick="window.remove('.$row['id'].');return false;" class="remove">remove</a></td>
              </tr>
            </table>'
    ));
    

    However the resulting code is still hard to read. If you are sending json data, it would make much more sense to just send the raw data and build the html client side with javascript.

    Failing that, i would suggest you use output buffering to invert the operation, eg echoing php variables into html string, rather than the current method of concatenating strings around variables:

    $img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
    $row=mysql_fetch_assoc(mysql_query("SELECT * FROM rooms_addons WHERE img='".$img."'"));
    //start output buffer
    ob_start();
    //exit php mode
    ?>
        <table width="65%" id="table_<?=$row['id']?>">
            <tr>
                <td width="5%" style="display:none;">
                    <input type="text" name="id[]" value="<?=$row['id']?>" style="width: 28px; border-width: 0px;"
                </td>
                <td width="35%">
                    <input type="text" name="roomname[]" value="<?=$row['name']?>" style="width: 95px; border-width: 0px;">
                </td>
                <td width="20%">Php 
                    <input type="text" name="price[]" value="<?=$row['price']?>" style="width: 40px; border-width: 0px;">
                </td>
                <td width="15%">
                    <?php $qty = $row["qty"];?>
                    <select name="<?=$row['id']?>_cnt" id="<?=$row['id']?>_cnt" onchange="change(<?=$row['id']?>);">
                        <?php for ($i=0;$i<=$qty;$i++) :?>
                        <option><?=$i?></option>
                        <?php endfor; ?>
                    </select>
                </td>
                <td width="15%"><a href="#" onclick="window.remove(<?=$row['id']?>);return false;" class="remove">remove</a></td>
            </tr>
        </table>
    
    <?php
    //get html from output buffer
    
    $html = ob_get_clean();
    echo json_encode(array(
        'status' => 1,
        'id' => $row['id'],
        'price' => (float)$row['price'],
        'txt' => $html
    ));
    ?>
    

    Finally mysql_* functions are depreciated, and removed from the current version of php - time to move to PDO instead

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'