剧本:
<?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);
}
}
?>
脚本打印:
Array ( [0] => 558 ) Array ( [0] => 559 ) Array ( [0] => 560 )
如何在 一个 数组中包含这些值?
E.g:
Array ( [0] => 558 [1] => 559 [2] => 560 )
图像文件名来自表单,值来自&#34;图像&#34;表。我希望将所选内容存储在 一个 数组中。
答案 0 :(得分:0)
问题是你正在销毁数组并在每次迭代时重新创建它。将该行移出循环,不要在每次迭代时打印数组:
$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
附注:您的查询容易受到SQL注入攻击。切换到带有绑定参数的Prepared语句。
答案 1 :(得分:0)
您必须在循环外声明您的数组。否则你会继续覆盖数组。
<?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);
$fetch_array = array(); // <----------- Declare here
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); // <----------- Print here
}
?>