所以我对foreach循环很新,似乎无法掌握这一点。我想从我的db中提取一个名为“something1”,“something2”等的未知数量的列。并且每列我想从每一行获取数据。类似于“something1:Apple,Pear,Grape”之类的内容,然后是下一篇专栏文章。
我使用以下链接上的foreach循环上传并计算行数和列数:
Foreach input php and mysql
我尝试过这样的一些事情
//Grabing DB above.
$Count = mysqli_num_rows($sql);
if($Count > 0){
while($row = mysqli_fetch_array($sql)){
$i = 0;
if ($type == "somethingrows"){
foreach ($row['something$i'] as $values){
$something_value = $values;
$i++;
}
$output .= "<option value='$something_value'>$something_value</option>";
}
}
}
非常欢迎任何想法或想法! 谢谢!
答案 0 :(得分:0)
你可以这样做。你需要改变一些设置。
test.php的:
//Use your connection data here
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//select column optionXX from table, maybe you need to change the column-name or/and table-name
$sql = "SELECT `optionXX` FROM `table`";
$query = mysqli_query($connect, $sql);
//put all records we have selected in an array to be used later in the HTML
while ($record = mysqli_fetch_array($query)){
$optionsArray[] = $record['optionXX'];
}
//check if there is set an option and the form is submitted
if(isset($_POST['submit']) && isset($_POST['option'])){
//select the row which was selected, , maybe you need to change the column-name or/and table-name
$sql = "SELECT * FROM `table` WHERE `optionXX` = '". $_POST['option'] . "'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_array($query);
}
?>
<!-- change path test.php to your file name -->
<form action="test.php" method="POST">
<select name="option">
<? foreach($optionsArray AS $option){ ?>
<option value="<? echo $option; ?>"><? echo $option; ?></option>
<? } ?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?
//when row is set
if(isset($row)) {
echo "Row " . $_POST['option'] . "<br><br>";
//iterate over array $row
foreach($row AS $key => $value){
echo $key . ": " . $value . "<br>";
}
}?>
答案 1 :(得分:0)
在第一个位置,
这违反了数据库架构的基本原则。
相反,您应该有一个单独的表,其中所有这些未知的列必须以行的形式存储,并通过唯一标识符链接到另一个表。所以,新表应该是这样的:
other table id | something
1 | foo
1 | bar
2 | foo
1 | baz
您可以通过单独的查询选择您的事物,然后在通常的循环中处理它们而不会出现任何复杂情况。
这是这类问题的唯一正确答案。