I want to select all even posts id's from a table in my MySQL db and then display them. I also want to get all posts with odd id's and display them somewhere else.
I want to do this with PHP since that is the server-side language I am using.
Alternatively, would I have to select all posts and then check if they are even/odd with JavaScript? I would prefer PHP, but if it works with JavaScript that would be fine too.
Example of what I want:
table:
==================================================
id | text
==================================================
==================================================
| 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. |
==================================================
| 2 | turpis quis aliquet commodo, urna quam viverra justo, in |
==================================================
| 3 | Etiam in lectus sem. Nullam molestie nisl vel nunc consectetur |
==================================================
| 4 | Vestibulum eu molestie sapien. Ut luctus nulla vel libero sagittis |
==================================================
my failed attempt at a table in stackoverflow ^^
I want to display the even ones first, and the odd ones second:
Even Rows:
turpis quis aliquet commodo, urna quam viverra justo, in
Vestibulum eu molestie sapien. Ut luctus nulla vel libero sagittis
Odd Rows:
Lorem ipsum dolor sit amet, consectetur adipiscing elit
Etiam in lectus sem. Nullam molestie nisl vel nunc consectetur
Syntax. To find and return the records with the odd or even values, the most simple way is to check the remainder when we divide the column value by 2. When the remainder is 0, that's an even number, otherwise, that's an odd number.
You are not using Oracle, so you should be using the modulus operator: SELECT * FROM Orders where OrderID % 2 = 0; The MOD() function exists in Oracle, which is the source of your confusion.
To select even or odd IDs from a MySQL table, you would use the modulo operator (like in PHP):
SELECT * FROM table WHERE (id % 2) = 0; # even SELECT * FROM table WHERE (id % 2) > 0; # odd
In order to select even or odd IDs from a MySQL table, you would use the 'MOD', this easy way to select the Odd and Even numbers.
Select Odd number
select column_name from table_name where mod(column_name,2)=1;
Select Even number
select column_name from table_name where mod(column_name,2)=0;
if you need an Odd number, put 1.
if you need an Even number, put 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With