0

This is the current PHP script I am using:

$query = "SELECT * FROM tbl WHERE status='Godkjent' AND team='{$_SESSION['team']}' ORDER BY date DESC LIMIT 5";

if ($result = $link->query($query)) {
      $num_rows = 0;
      while ($row = $result->fetch_assoc()) {
          $num_rows++;
          
          
          echo "{$row['pp']}";
          
          // determine if user has already liked this post
          $results = mysqli_query($link, "SELECT * FROM kudos WHERE sale_id='{$row['id']}' AND ident_id='{$_SESSION["ident"]}'");
          $resultSet = $link->query("SELECT kudos.sale_id as TheID, kudos.ident_id AS TheIdent from kudos,tbl where kudos.sale_id = '{$row['id']}' AND tbl.id = kudos.sale_id");
          if (mysqli_num_rows($results) == 0 ) { // Not liked
              echo "<a style='color:#FFFFFF' class='btn' href='kudos.php?id={$row['id']}'>  $resultSet->num_rows </a>"; // Gonna remove this
          } else { // Has liked
              echo "<b style='color:#FFFFFF' class='btn'>  $resultSet->num_rows </b>"; // Gonna remove this
          }
      }
      /*freeresultset*/
      $result->free();
  }

Shortly explained the results and resultSet query: Check if current user has liked post. Display total number of likes for each 5 posts. Do not like user like post again if already liked.

So I am query'ing the last 5 rows from tbl table. And inside that query, I have another query that selects all the values from kudos table where sale_id is equal to the first query's row ID. I know the solution I am using now is NOT safe agains SQL Injections, so I am trying to look into prepared statements. Can someone help me transform these questions to prepared statements?

Erik Auranaune
  • 1,384
  • 1
  • 12
  • 27
  • Surely you can do [research](https://meta.stackoverflow.com/q/261592/1422451) across the many posts on PHP `mysqli` prepare statements and then give it an earnest try. Please do and come back with specific issues on attempts. – Parfait Sep 20 '20 at 02:20

1 Answers1

-1

There's a really simple library you can use that uses prepared statements called Simple PDO.

Using that, you would do something like this:

$results = $db->select("SELECT * FROM tbl 
    WHERE status = :status 
    AND team = :team
    ORDER BY date DESC LIMIT 5", [
        'status' => 'Godkjent',
        'team' => $_SESSION['team']
    ]
);
MultiDev
  • 10,389
  • 24
  • 81
  • 148