Reputation: 459
my last question was no quite good, so im sorry to "open" new one.
Importante data:
Table1
Table2
Query1 (id Results):
Query2 (id Results):
So, I have a checkbox that need to be changed to "checked" if everytime that I fetch these 2 tables (with proper query ofc) and some id from table2 exists on table1.
Im doing like this:
<?php
while($row = mysql_fetch_array($Query1))
{
while($row2 = mysql_fetch_array($Query2))
{
$checkit = '';
if($row['id'] == $row2['id'] )
$checkit = 'checked="checked"';
}
?>
<input type="checkbox" name = "checkbox-1" class="checkbox" value ="" <?php echo $checkit ?> />
<?php
}
}
?>
Problem: I just can have "checked" for the first result, when 1=1.
That While fetch only once. I need that the result should be like this (id): 11-13 | 21-23 |31-33 and checked checkbox should appear only when 11 and 33
I hope that you understand this..
Upvotes: 0
Views: 1299
Reputation: 1856
I would do:
$t2data = array();
while($row2 = mysql_fetch_assoc($Query2)) {
$t2data[] = $row2[0];
}
while($row1 = mysql_fetch_assoc($Query1)) {
if(in_array($row1[0], $t2data)) {
$checked = 'checked';
}
}
That being said, if both of the tables are in the same database, this is best solved with an OUTER JOIN query:
select t1.id, (t2.t1_id IS NOT NULL) as checked
from t1
left join t2 on (t1.id = t2.t1_id)
Then loop over the results and check only the boxes where checked=true from the query.
Upvotes: 1
Reputation: 425
You will need to reset your internal result pointer after the internal while block.
while($row = mysql_fetch_array($Query1))
{
while($row2 = mysql_fetch_array($Query2))
{
// Your code
}
mysql_data_seek($Query2,0);
}
Upvotes: 1
Reputation: 7762
you have use
$checkit = 'checked="yes"';
should be
$checkit = 'checked="checked"';
try this:--
<?php
$arr_one = '';
while($row = mysql_fetch_array($Query1))
{
$arr_one[]= $row['id'];
}
while($row2 = mysql_fetch_array($Query2))
{
$checkit = '';
$id = $row2['id'];
if (in_array($id,$arr_one))
{
$checkit = 'checked="checked"';
}
?>
<input type="checkbox" name= "checkbox-1" class="checkbox" value ="" <?php echo $checkit ?> />
<?php
}
?>
Upvotes: 1