Быстро просматривая ваш код, я думаю, вы могли бы его немного изменить
<?php
session_start();
/*
`fruit` and `color` MUST be available
before attempting to assign as any
sort of variable - so test here!
*/
if( isset(
$_POST['submit'],
$_POST['fruit'],
$_POST['color']
)){
include('connection.php');
/*
It is not entirely clear why you would want to assign
session values directly from POST values when you could
simply work with the POST values instead.
*/
$fruits=$_POST['fruit'];
$colours=$_POST['color'];
/*
create the sql statement with placeholders
which are then bound as parameters when the
statement is executed.
Create the statement once and assign new values
inside of any loops rather than re-stating it
on each iteration.
*/
$sql='select `col1`, `col2`, ( select `democol` from `tbl_colors` where `c_id`=:cid ) as `democolor`
from `tbl_mytable`
where `id`=:id and `is_active`=1';
$stmt=$pdo->prepare( $sql );
/*
Process the POSTed variables
using the $key to access the values
within the other array ( colours )
*/
foreach( $fruits as $key => $value ) {
try{
if( isset( $colours[ $key ] ) ){
$stmt->execute( array(
':cid' => $value,
':id' => $colours[ $key ]
));
$result = $stmt->fetchAll();
foreach( $result as $row ) {
?>
<h3>
<?php echo $row['col1'];?>
<?php echo $row['col2'];?>
</h3>
<p><?php echo $row['demoColor'];?></p>
<?php
}
}
} catch( PDOException $e ) {
echo "Error: " . $e->getMessage();
}
}
}
?>
При более внимательном рассмотрении можно предположить, что у вас, вероятно, может быть только один SQL запрос для извлечения всех записей путем первоначальной обработки POST data и создание подходящих строк, содержащих различные идентификаторы, чтобы вы использовали оператор IN
в sql - например, where id IN (1,2,3)
et c - например:
$sql='select `col1`, `col2`, ( select `democol` from `tbl_colors` where `c_id` IN ( :cids ) ) as `democolor`
from `tbl_mytable`
where `id` IN ( :ids ) and `is_active`=1';
$stmt=$pdo->prepare( $sql );
$args=array(
':cids' => implode(',',array_values( $colours ) ),
':ids' => implode(',',array_values( $fruits ) )
);
$stmt->execute( $args );
Надеюсь, это может будет полезно - я должен подчеркнуть, что ни один из них не был протестирован, поэтому могут быть ошибки, но надеюсь, что нет.