duanjia4097 2014-10-16 11:28
浏览 16
已采纳

在一个数组中有多个值 - For Loop?

The Script:

<?php
        include("connect.php");    
?>    
<form method="POST" action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="name1" />
    <input type="text" name="name2" />
    <input type="text" name="name3" />
    <input type="submit" name="submit" />
</form>    
<?php
if(isset($_POST['submit'])){    
    $name1 = $_POST['name1'];
    $name2 = $_POST['name2'];
    $name3 = $_POST['name3'];

    $myarray = array($name1, $name2, $name3);   

    for($i = 0; $i < count($myarray); $i++){

        $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('" . $myarray[$i] . "')";
        $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));

        $fetch_array = array();
        $row = mysqli_fetch_array($tqr);
        $fetch_array[] = $row['id'];

        print_r($fetch_array);    
    }    
}    
?>

The script prints:

Array ( [0] => 558 ) Array ( [0] => 559 ) Array ( [0] => 560 ) 

How to have these values inside one array?

E.g.:

Array ( [0] => 558 [1] => 559 [2] => 560 )

The image file names come from the form and the values come from the ID column of the "images" table. And I am looking to have the selected stored inside one array.

  • 写回答

2条回答 默认 最新

  • dqs13465424392 2014-10-16 11:31
    关注

    The issue is you're destroying the array and recreating it on each iteration. Move that line out of the loop, and don't print the array on each iteration:

    $fetch_array = array(); // only create the array once
    
    for($i = 0; $i < count($myarray); $i++){
        $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('" . $myarray[$i] . "')";
        $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
    
        $row = mysqli_fetch_array($tqr);
        $fetch_array[] = $row['id'];
    }
    
    print_r($fetch_array); // only output once
    

    Side note: your query is vulnerable to SQL Injection. Switch to a Prepared Statement with bound parameters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题