dsh8009271 2015-10-07 16:00
浏览 6
已采纳

PHP Text Area到MySQL查询变量不会返回所有行结果

I am using a text area in order allow searching of multiple items at once and output the results to a table. Everything works fine when only one item is placed into the text area and searched, however the query results of the first line/search item are not returned if more than one item is searched. My code:

<textarea name="search_items" rows="2" cols="30"></textarea>

$input = $_POST['search_items'];
list($pc1, $pc2) = explode("
", $input);

$desc = mysqli_query($my_connection,"SELECT PART_DESC FROM inventory WHERE PARTCODE = '$pc1' OR PARTCODE = '$pc2';");

$i=1;
while($row_desc = mysqli_fetch_assoc($desc)) { 
    ${'pc_desc'.$i} = $row_desc['PART_DESC']; 
    $i++; 
} 

<table>
    <tr>
        <td><?php echo "$pc1"; ?></td>
        <td><?php echo $pc_desc1; ?></td>
    </tr>
    <tr>
        <td><?php echo "$pc2"; ?></td>
        <td><?php echo $pc_desc2; ?></td>
    </tr>
</table>

$pc1 echos out line 1 of the text area and $pc2 echos out line 2 of the text area. I get the correct results echoed out for $pc_desc2 but $pc_desc1 is blank. If I manually assign $pc1 and $pc2 like this:

$pc1 = "ABC";
$pc1 = "XYZ";

both $pc_desc1 and $pc_desc2 return correctly. Please Help!

  • 写回答

1条回答 默认 最新

  • doushang8846 2015-10-07 16:07
    关注

    Without fixing your SQL injection problems, you'd be better off using something like this:

    ...
    $parts = explode("
    ", $input);
    $sql = "SELECT ... PARTCODE IN (" . implode(',', $parts) . ");";
    ...
    while($row_desc = mysqli_fetch_assoc($desc)) { 
        $data[$row['PART_CODE']] = $row['PART_DESC'];
    }
    
    <table>
    
    foreach($data as $code => $desc) {
        echo "<tr><td>$code</td><td>$desc</td></tr>
    }
    

    With your code, you have NO guarantee which order the descriptions come back in, and could end up "crossing" things, so you have part #1 with description #2, and part #2 with description #1. The above code guarantees that codes/descriptions are always properly associated together. And also dispenses with dynamic variable names, which make for difficult-/impossible-to-debug code. As well, the above code could handle an arbitrary number of codes, while yours is limited to 2.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献