Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# if all rows found are equal to each other

Posted on 2013-11-20
Medium Priority
277 Views
How can we use if statement inside the foreach loop below to check whether all the row values (no matter what their count is) returned by the mysql query are equal to each other?

\$query = "SELECT field_qty_item FROM ...";
foreach (\$query as \$row) {

if all \$row values returned are equal to each other...
// do smthng

}
else {
// do nothing... or do another thing...
}
0
Question by:sbayrak
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 32

Expert Comment

ID: 39664471
There are many ways ... but this should work.
``````\$FirstValSet = false;
\$FoundMismatch = false;

\$query = "SELECT field_qty_item FROM ...";
foreach (\$query as \$row) {
if (!\$FirstValSet){
\$val = \$row[0];
\$FirstValSet = true;
}else{
if (\$row[0] != \$val){
\$FoundMismatch=true;
break;
}
}
}
if all \$row values returned are equal to each other...
if (!\$FoundMismatch){
// do smthng

}
else {
// do nothing... or do another thing...
}
``````
0

LVL 35

Accepted Solution

Terry Woods earned 2000 total points
ID: 39664564
\$query = "SELECT count(distinct field_qty_item) FROM ...";

if result == 1 then
#they are all the same
else
#they're not
0

LVL 44

Expert Comment

ID: 39665291
What exactly are you trying to achieve. Maybe the IF statement isn't the best way forward.

You can have a GROUP BY clause in your SQL Statement:

``````SELECT count(field_qty_item) as Amount, field_qty_item FROM yourTable GROUP BY field_qty_item
``````
You would then only get unique values of field_qty_item, along with an Amount of how many times each value exists in the database. If you only get 1 record returned then clearly all the rows match each other.
0

LVL 1

Author Closing Comment

ID: 39667005
smooth
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to implement server side field validation and display customized error messages to the client.
This post contains step-by-step instructions for setting up alerting in Percona Monitoring and Management (PMM) using Grafana.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrasâ€¦
###### Suggested Courses
Course of the Month10 days, 10 hours left to enroll