0

I have simple code in PHP and MySQL and Im trying to change LIMIT in MySQL query on click.

I found following method on stackoverflow but nnot working.

I want when someone click on the button LIMIT will be changed from 0 and 11 to 11 and 22. So I make if statement when $_POST exists to variable which holds values 0 and 11 will be added 11 to both. But my code dont working.

My code:

if ( $_POST ) {

    $limit1 += 11;
    $limit2 += 11;

} else {
    $limit1 = 0;
    $limit2 = 11;
}

?>
<h2>DOKUMENTY</h2>
<div class="ciara"></div>
<ul class="doc-list">
    <?php
        if ($db->connect_error) {
            die("Not connected: " . 
$db->connect_error);
        }

        $sql = "SELECT * FROM (
                SELECT * FROM upload 
                ORDER BY id DESC 
                LIMIT $limit1, $limit2
                ) sub
                ORDER BY id DESC";
        $result = $db->query($sql);

        if ($result->num_rows) {
            while ($row = $result->fetch_assoc()) {
                echo '<li class="'.($row['id'] % 2 == 0 ? 'light' : 'dark').'"><a href="'. $row["location"] .'">' . $row["headline"] . "</a></li>";
            }
        }
    ?>
</ul>

<form method="post">
    <input type="hidden" value="g">
   <input type="submit" value="Next"> 
</form>
4
  • If you want a variable to persist between different postings to the server, you need to use a session variable. Commented Jul 2, 2019 at 18:56
  • Can u help me with it? IM not sure what you mean. Commented Jul 2, 2019 at 19:01
  • 1
    w3schools.com/php/php_sessions.asp Commented Jul 2, 2019 at 19:02
  • Using GET instead of POST could be a poor man's approach to *persisting" this? Commented Jul 2, 2019 at 19:05

1 Answer 1

1

Just add another hidden input field in your form to retain last value.

<input type="hidden" name="limit" value="<?= $limit ?>">

and then change your php if condition to

if ( $_POST['submit'] ) {

    $limit1 += (int) $_POST['limit'] + 11; // adding previous value i.e 0 + 11 = 11;
    $limit2 += (int) $_POST['limit'] + 11; // 11 + 11 = 22;

} else {
    $limit1 = 0;
    $limit2 = 11;
}

but also make sure if you have more records to show in your database and set that limit accordingly.

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

1 Comment

you do not have $limit variable it will not be available once page reloads so you need to keep previous value too.

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.