PHP PDO search & pagination












0












$begingroup$


I know that OOP is ubiquitous nowadays. Nonetheless I still write procedural PHP. It now seems to me that I had fallen into a spaghetti code trap, because my code starts to seem meaningless even to me (it's author :)



Can you please tell me how bad is this?



<?php
/**
* Created by PhpStorm.
* User: Taras
* Date: 23.01.2019
* Time: 20:01
*/

include "db_conn.php";
$currentPage = "list";
include "header.php";

// Quantity of results per page
$limit = 10;

// Check if page has been clicked
if (!isset($_GET['page'])) {
$page = 1;
} else{
$page = $_GET['page'];
}

// Initial offset, if page number wasn't specified than start from the very beginning
$starting_limit = ($page-1)*$limit;

// Check if search form has been submitted
if (isset($_GET['search'])) {
$searchTerm = $_GET['search'];

$sql = "SELECT company.id, company.name, inn, ceo, city, phone
FROM company
LEFT JOIN address ON company.id = address.company_id
LEFT JOIN contact ON company.id = contact.company_id
WHERE
MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
OR MATCH (city, street) AGAINST (:searchTerm)
OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':searchTerm' => $searchTerm));

$total_results_without_limit = $stmt->rowCount();
$total_pages = ceil($total_results_without_limit/$limit);

$sql = "SELECT company.id, company.name, inn, ceo, city, phone
FROM company
LEFT JOIN address ON company.id = address.company_id
LEFT JOIN contact ON company.id = contact.company_id
WHERE
MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
OR MATCH (city, street) AGAINST (:searchTerm)
OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)
ORDER BY id DESC LIMIT $starting_limit, $limit";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':searchTerm' => $searchTerm));
// Count number of rows to make proper number of pages

} else { // Basically else clause is similar to the search block except no search is being made
$sql = "SELECT * FROM company";
$stmt = $pdo->prepare($sql);
$stmt->execute();

// Again count number of rows
$total_results = $stmt->rowCount();
$total_pages = ceil($total_results/$limit);
// And then make a query
$stmt = $pdo->prepare("
SELECT company.id, company.name, company.inn,
company.ceo, address.city, contact.phone
FROM company
LEFT JOIN address
ON company.id = address.company_id
LEFT JOIN contact
ON company.id = contact.company_id
ORDER BY id ASC LIMIT $starting_limit, $limit");
$stmt->execute();
}
?>

<main class="container">
<section class="section-search">
<div class="row col-auto">
<h2>Найти компанию</h2>
</div>
<form action="list.php" method="get">
<div class="row">
<div class="form-group col-lg-6 col-md-6 col-sm-12 row">
<label class="col-sm-4 col-form-label" for="searchTerm">
Поиск
</label>
<input type="text" class="form-control col-sm-8"
id="companyTerm" name="search">
</div>
<div class="float-right">
<input type="submit" class="btn btn-primary mb-2" value="Поиск">
</div>
</div>
</form>
</section>


<section class="section-companies">
<table class="table table-sm">
<thead>
<tr>
<th scope="col">ИНН</th>
<th scope="col">Название</th>
<th scope="col">Генеральный директор</th>
<th scope="col">Город</th>
<th scope="col">Контактный телефон</th>
</tr>
</thead>
<tbody>
<?php
// Filling the result table with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td scope='row'>" . $row['inn'] . "</td>";
echo "<td><a href='company.php?id=" . $row["id"] . "'>" . $row['name'] . "</a>" . "</td>";
echo "<td>" . $row['ceo'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['phone'] . "</td></tr>";
}
?>

</tbody>
</table>
</section>
<?php

// Paginating part itself
for ($page=1; $page <= $total_pages ; $page++):?>

<a href='<?php
if (isset($searchTerm)) {
echo "list.php?search=$searchTerm&page=$page";
} else {
echo "list.php?page=$page";
} ?>' class="links"><?php echo $page; ?>
</a>

<?php endfor; ?>
</main>









share|improve this question







New contributor




tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    I know that OOP is ubiquitous nowadays. Nonetheless I still write procedural PHP. It now seems to me that I had fallen into a spaghetti code trap, because my code starts to seem meaningless even to me (it's author :)



    Can you please tell me how bad is this?



    <?php
    /**
    * Created by PhpStorm.
    * User: Taras
    * Date: 23.01.2019
    * Time: 20:01
    */

    include "db_conn.php";
    $currentPage = "list";
    include "header.php";

    // Quantity of results per page
    $limit = 10;

    // Check if page has been clicked
    if (!isset($_GET['page'])) {
    $page = 1;
    } else{
    $page = $_GET['page'];
    }

    // Initial offset, if page number wasn't specified than start from the very beginning
    $starting_limit = ($page-1)*$limit;

    // Check if search form has been submitted
    if (isset($_GET['search'])) {
    $searchTerm = $_GET['search'];

    $sql = "SELECT company.id, company.name, inn, ceo, city, phone
    FROM company
    LEFT JOIN address ON company.id = address.company_id
    LEFT JOIN contact ON company.id = contact.company_id
    WHERE
    MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
    OR MATCH (city, street) AGAINST (:searchTerm)
    OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':searchTerm' => $searchTerm));

    $total_results_without_limit = $stmt->rowCount();
    $total_pages = ceil($total_results_without_limit/$limit);

    $sql = "SELECT company.id, company.name, inn, ceo, city, phone
    FROM company
    LEFT JOIN address ON company.id = address.company_id
    LEFT JOIN contact ON company.id = contact.company_id
    WHERE
    MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
    OR MATCH (city, street) AGAINST (:searchTerm)
    OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)
    ORDER BY id DESC LIMIT $starting_limit, $limit";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':searchTerm' => $searchTerm));
    // Count number of rows to make proper number of pages

    } else { // Basically else clause is similar to the search block except no search is being made
    $sql = "SELECT * FROM company";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    // Again count number of rows
    $total_results = $stmt->rowCount();
    $total_pages = ceil($total_results/$limit);
    // And then make a query
    $stmt = $pdo->prepare("
    SELECT company.id, company.name, company.inn,
    company.ceo, address.city, contact.phone
    FROM company
    LEFT JOIN address
    ON company.id = address.company_id
    LEFT JOIN contact
    ON company.id = contact.company_id
    ORDER BY id ASC LIMIT $starting_limit, $limit");
    $stmt->execute();
    }
    ?>

    <main class="container">
    <section class="section-search">
    <div class="row col-auto">
    <h2>Найти компанию</h2>
    </div>
    <form action="list.php" method="get">
    <div class="row">
    <div class="form-group col-lg-6 col-md-6 col-sm-12 row">
    <label class="col-sm-4 col-form-label" for="searchTerm">
    Поиск
    </label>
    <input type="text" class="form-control col-sm-8"
    id="companyTerm" name="search">
    </div>
    <div class="float-right">
    <input type="submit" class="btn btn-primary mb-2" value="Поиск">
    </div>
    </div>
    </form>
    </section>


    <section class="section-companies">
    <table class="table table-sm">
    <thead>
    <tr>
    <th scope="col">ИНН</th>
    <th scope="col">Название</th>
    <th scope="col">Генеральный директор</th>
    <th scope="col">Город</th>
    <th scope="col">Контактный телефон</th>
    </tr>
    </thead>
    <tbody>
    <?php
    // Filling the result table with results
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr><td scope='row'>" . $row['inn'] . "</td>";
    echo "<td><a href='company.php?id=" . $row["id"] . "'>" . $row['name'] . "</a>" . "</td>";
    echo "<td>" . $row['ceo'] . "</td>";
    echo "<td>" . $row['city'] . "</td>";
    echo "<td>" . $row['phone'] . "</td></tr>";
    }
    ?>

    </tbody>
    </table>
    </section>
    <?php

    // Paginating part itself
    for ($page=1; $page <= $total_pages ; $page++):?>

    <a href='<?php
    if (isset($searchTerm)) {
    echo "list.php?search=$searchTerm&page=$page";
    } else {
    echo "list.php?page=$page";
    } ?>' class="links"><?php echo $page; ?>
    </a>

    <?php endfor; ?>
    </main>









    share|improve this question







    New contributor




    tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I know that OOP is ubiquitous nowadays. Nonetheless I still write procedural PHP. It now seems to me that I had fallen into a spaghetti code trap, because my code starts to seem meaningless even to me (it's author :)



      Can you please tell me how bad is this?



      <?php
      /**
      * Created by PhpStorm.
      * User: Taras
      * Date: 23.01.2019
      * Time: 20:01
      */

      include "db_conn.php";
      $currentPage = "list";
      include "header.php";

      // Quantity of results per page
      $limit = 10;

      // Check if page has been clicked
      if (!isset($_GET['page'])) {
      $page = 1;
      } else{
      $page = $_GET['page'];
      }

      // Initial offset, if page number wasn't specified than start from the very beginning
      $starting_limit = ($page-1)*$limit;

      // Check if search form has been submitted
      if (isset($_GET['search'])) {
      $searchTerm = $_GET['search'];

      $sql = "SELECT company.id, company.name, inn, ceo, city, phone
      FROM company
      LEFT JOIN address ON company.id = address.company_id
      LEFT JOIN contact ON company.id = contact.company_id
      WHERE
      MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
      OR MATCH (city, street) AGAINST (:searchTerm)
      OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)";
      $stmt = $pdo->prepare($sql);
      $stmt->execute(array(':searchTerm' => $searchTerm));

      $total_results_without_limit = $stmt->rowCount();
      $total_pages = ceil($total_results_without_limit/$limit);

      $sql = "SELECT company.id, company.name, inn, ceo, city, phone
      FROM company
      LEFT JOIN address ON company.id = address.company_id
      LEFT JOIN contact ON company.id = contact.company_id
      WHERE
      MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
      OR MATCH (city, street) AGAINST (:searchTerm)
      OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)
      ORDER BY id DESC LIMIT $starting_limit, $limit";
      $stmt = $pdo->prepare($sql);
      $stmt->execute(array(':searchTerm' => $searchTerm));
      // Count number of rows to make proper number of pages

      } else { // Basically else clause is similar to the search block except no search is being made
      $sql = "SELECT * FROM company";
      $stmt = $pdo->prepare($sql);
      $stmt->execute();

      // Again count number of rows
      $total_results = $stmt->rowCount();
      $total_pages = ceil($total_results/$limit);
      // And then make a query
      $stmt = $pdo->prepare("
      SELECT company.id, company.name, company.inn,
      company.ceo, address.city, contact.phone
      FROM company
      LEFT JOIN address
      ON company.id = address.company_id
      LEFT JOIN contact
      ON company.id = contact.company_id
      ORDER BY id ASC LIMIT $starting_limit, $limit");
      $stmt->execute();
      }
      ?>

      <main class="container">
      <section class="section-search">
      <div class="row col-auto">
      <h2>Найти компанию</h2>
      </div>
      <form action="list.php" method="get">
      <div class="row">
      <div class="form-group col-lg-6 col-md-6 col-sm-12 row">
      <label class="col-sm-4 col-form-label" for="searchTerm">
      Поиск
      </label>
      <input type="text" class="form-control col-sm-8"
      id="companyTerm" name="search">
      </div>
      <div class="float-right">
      <input type="submit" class="btn btn-primary mb-2" value="Поиск">
      </div>
      </div>
      </form>
      </section>


      <section class="section-companies">
      <table class="table table-sm">
      <thead>
      <tr>
      <th scope="col">ИНН</th>
      <th scope="col">Название</th>
      <th scope="col">Генеральный директор</th>
      <th scope="col">Город</th>
      <th scope="col">Контактный телефон</th>
      </tr>
      </thead>
      <tbody>
      <?php
      // Filling the result table with results
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo "<tr><td scope='row'>" . $row['inn'] . "</td>";
      echo "<td><a href='company.php?id=" . $row["id"] . "'>" . $row['name'] . "</a>" . "</td>";
      echo "<td>" . $row['ceo'] . "</td>";
      echo "<td>" . $row['city'] . "</td>";
      echo "<td>" . $row['phone'] . "</td></tr>";
      }
      ?>

      </tbody>
      </table>
      </section>
      <?php

      // Paginating part itself
      for ($page=1; $page <= $total_pages ; $page++):?>

      <a href='<?php
      if (isset($searchTerm)) {
      echo "list.php?search=$searchTerm&page=$page";
      } else {
      echo "list.php?page=$page";
      } ?>' class="links"><?php echo $page; ?>
      </a>

      <?php endfor; ?>
      </main>









      share|improve this question







      New contributor




      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I know that OOP is ubiquitous nowadays. Nonetheless I still write procedural PHP. It now seems to me that I had fallen into a spaghetti code trap, because my code starts to seem meaningless even to me (it's author :)



      Can you please tell me how bad is this?



      <?php
      /**
      * Created by PhpStorm.
      * User: Taras
      * Date: 23.01.2019
      * Time: 20:01
      */

      include "db_conn.php";
      $currentPage = "list";
      include "header.php";

      // Quantity of results per page
      $limit = 10;

      // Check if page has been clicked
      if (!isset($_GET['page'])) {
      $page = 1;
      } else{
      $page = $_GET['page'];
      }

      // Initial offset, if page number wasn't specified than start from the very beginning
      $starting_limit = ($page-1)*$limit;

      // Check if search form has been submitted
      if (isset($_GET['search'])) {
      $searchTerm = $_GET['search'];

      $sql = "SELECT company.id, company.name, inn, ceo, city, phone
      FROM company
      LEFT JOIN address ON company.id = address.company_id
      LEFT JOIN contact ON company.id = contact.company_id
      WHERE
      MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
      OR MATCH (city, street) AGAINST (:searchTerm)
      OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)";
      $stmt = $pdo->prepare($sql);
      $stmt->execute(array(':searchTerm' => $searchTerm));

      $total_results_without_limit = $stmt->rowCount();
      $total_pages = ceil($total_results_without_limit/$limit);

      $sql = "SELECT company.id, company.name, inn, ceo, city, phone
      FROM company
      LEFT JOIN address ON company.id = address.company_id
      LEFT JOIN contact ON company.id = contact.company_id
      WHERE
      MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
      OR MATCH (city, street) AGAINST (:searchTerm)
      OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)
      ORDER BY id DESC LIMIT $starting_limit, $limit";
      $stmt = $pdo->prepare($sql);
      $stmt->execute(array(':searchTerm' => $searchTerm));
      // Count number of rows to make proper number of pages

      } else { // Basically else clause is similar to the search block except no search is being made
      $sql = "SELECT * FROM company";
      $stmt = $pdo->prepare($sql);
      $stmt->execute();

      // Again count number of rows
      $total_results = $stmt->rowCount();
      $total_pages = ceil($total_results/$limit);
      // And then make a query
      $stmt = $pdo->prepare("
      SELECT company.id, company.name, company.inn,
      company.ceo, address.city, contact.phone
      FROM company
      LEFT JOIN address
      ON company.id = address.company_id
      LEFT JOIN contact
      ON company.id = contact.company_id
      ORDER BY id ASC LIMIT $starting_limit, $limit");
      $stmt->execute();
      }
      ?>

      <main class="container">
      <section class="section-search">
      <div class="row col-auto">
      <h2>Найти компанию</h2>
      </div>
      <form action="list.php" method="get">
      <div class="row">
      <div class="form-group col-lg-6 col-md-6 col-sm-12 row">
      <label class="col-sm-4 col-form-label" for="searchTerm">
      Поиск
      </label>
      <input type="text" class="form-control col-sm-8"
      id="companyTerm" name="search">
      </div>
      <div class="float-right">
      <input type="submit" class="btn btn-primary mb-2" value="Поиск">
      </div>
      </div>
      </form>
      </section>


      <section class="section-companies">
      <table class="table table-sm">
      <thead>
      <tr>
      <th scope="col">ИНН</th>
      <th scope="col">Название</th>
      <th scope="col">Генеральный директор</th>
      <th scope="col">Город</th>
      <th scope="col">Контактный телефон</th>
      </tr>
      </thead>
      <tbody>
      <?php
      // Filling the result table with results
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo "<tr><td scope='row'>" . $row['inn'] . "</td>";
      echo "<td><a href='company.php?id=" . $row["id"] . "'>" . $row['name'] . "</a>" . "</td>";
      echo "<td>" . $row['ceo'] . "</td>";
      echo "<td>" . $row['city'] . "</td>";
      echo "<td>" . $row['phone'] . "</td></tr>";
      }
      ?>

      </tbody>
      </table>
      </section>
      <?php

      // Paginating part itself
      for ($page=1; $page <= $total_pages ; $page++):?>

      <a href='<?php
      if (isset($searchTerm)) {
      echo "list.php?search=$searchTerm&page=$page";
      } else {
      echo "list.php?page=$page";
      } ?>' class="links"><?php echo $page; ?>
      </a>

      <?php endfor; ?>
      </main>






      php pdo






      share|improve this question







      New contributor




      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 18 mins ago









      tnsaturdaytnsaturday

      1




      1




      New contributor




      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      tnsaturday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          tnsaturday is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212958%2fphp-pdo-search-pagination%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          tnsaturday is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          tnsaturday is a new contributor. Be nice, and check out our Code of Conduct.













          tnsaturday is a new contributor. Be nice, and check out our Code of Conduct.












          tnsaturday is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212958%2fphp-pdo-search-pagination%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар