Reputation: 352
I want to access rows from a table with matching values, In my table, I have 3 columns each column may contain 1 or 0 like below
column1 column2 column3
1 0 0
0 1 0
0 0 1
1 1 0
0 0 1
0 1 0
. . .
. . .
This is what I tried
$query = "SELECT column1, column2, column3 FROM tableName LIMIT 10";
$Res = $connection->query($query);
if($Res->rowCount() > 0) {
while($rows = $Res->fetch(PDO::FETCH_ASSOC)) {
if($rows['column1'] == 1) {
//body
}
if($rows['column2'] == 1) {
//body
}
if($rows['column3'] == 1) {
//body
}
}
}
but here I am not getting each column with 10 rows.
Upvotes: 2
Views: 68
Reputation: 28522
You have given limit 10
so it will fetch 10 rows only from table without looking if there are 0's
or 1's
in that column ,so to overcome this one way is to remove limit 10
instead used count
to keep count of 1's
and only print 10 rows
. Like below :
$query = "SELECT column1, column2, column3 FROM tableName ";
$Res = $connection->query($query);
//counter for getting rows having 1's
c=0;
c1=0;
c2=0;
if($Res->rowCount() > 0) {
while($rows = $Res->fetch(PDO::FETCH_ASSOC)) {
if($rows['column1'] == 1) {
//checking if counter is < = to 10
if(c<=10){
//do something
c++;
}
}
if($rows['column2'] == 1) {
if(c1<=10){
//do something
c1++;
}
}
if($rows['column3'] == 1) {
if(c2<=10){
//do something
c2++;
}
}
}
}
Upvotes: 1