0

I have this code for mysql query.

$sql = "SELECT * FROM `".$data."` 
UNION
SELECT d2.* FROM `".$data2."` d2
WHERE NOT EXISTS (SELECT 1 FROM `".$data."` d1 WHERE d1.id = d2.id)
AND created_at >= NOW() - INTERVAL 35 HOUR
LIMIT 50
";


if (isset($_GET['page-2'])) {
    $sql = "SELECT * FROM `".$data."` 
    UNION
    SELECT d2.* FROM `".$data2."` d2
    WHERE NOT EXISTS (SELECT 1 FROM `".$data."` d1 WHERE d1.id = d2.id)
    AND created_at >= NOW() - INTERVAL 35 HOUR
    LIMIT 50,50
    ";
}


if (isset($_GET['page-3'])) {
    $sql = "SELECT * FROM `".$data."` 
    UNION
    SELECT d2.* FROM `".$data2."` d2
    WHERE NOT EXISTS (SELECT 1 FROM `".$data."` d1 WHERE d1.id = d2.id)
    AND created_at >= NOW() - INTERVAL 35 HOUR
    LIMIT 100,50
    ";
}

How yo can see, i have pages example.com/?page-2, example.com/?page-3, example.com/?page-4 and etc.. For every page with numerical get parameter i have separate mysql query.

What is the best way to optimize code?

1 Answer 1

1

Try this

    <?php

    // If pageNo given
    if(sizeof($_GET) > 0){
        $pageGetKey = array_keys($_GET)[0];
        $pageNo = explode("-", $pageGetKey)[1];
    } else{

        // If no pageNo given
        $pageNo = 0;
    }
    
    
    echo $pageNo;

    $limitMin = $pageNo * 50;
    $limitMax = $limitMin + 50;



    $sql = "SELECT * FROM `".$data."` UNION SELECT d2.* FROM `".$data2."` d2 WHERE NOT EXISTS (SELECT 1 FROM `".$data."` d1 WHERE d1.id = d2.id) AND created_at >= NOW() - INTERVAL 35 HOUR LIMIT ".$limitMin." , ".$limitMax;


?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.