简体   繁体   中英

How to grab information from a url and use it in a php function?

I want to make a function that selects every field with a specific criteria. So basically I want to click on a link and let some part of that link tell my php function what the criteria for the selection is.

I have a list of links like this:

<li><a href="category.php?category=cat1">Cat1</a></li>
<li><a href="">Cat2</a></li>
<li><a href="">Cat3</a></li>
<li><a href="">Cat4</a></li>
<li><a href="">Cat5</a></li>

The part of the link is .php?category=criteria . How can I send this information to my function and use it to select the fields?

This is the function I have:

public function get_by_category ($cat) {
  $cat = $_GET['category'];
  $sql = $this->db->prepare("SELECT * FROM Content WHERE category=?");
  $sql->bindParam(1, $cat);
  $sql->execute();

  while ($row = $sql->fetch()) {
    echo $row['Title'];
  }
}

The result is nothing, no errors etc. it doesn't know how to get the criteria because I don't know how to direct the criteria to it. How can I make this work? It's important that I could specify the criteria through the link.

Using PDO with named parameters usually works:

public function get_by_category ($cat) {
  $cat = $_GET['category'];
  $sql = $this->db->prepare("SELECT * WHERE category=:category");
  $sql->bindParam("category", $cat);
  $sql->execute();

  while ($row = $sql->fetch()) {
    echo $row['Title'];
  }
}

You can see what SQL is being executed by placing a print $sql->fullStmt to inspect the prepared statement before it gets send to SQL.

Update: in order to see PDO exceptions, you can try-catch them:

public function get_by_category ($cat) {
  $cat = $_GET['category'];
  try {
    $sql = $this->db->prepare("SELECT * WHERE category=:category");
    $sql->bindParam("category", $cat);
    $sql->execute();
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }

  while ($row = $sql->fetch()) {
    echo $row['Title'];
  }
}

Passing the $cat value to your query should do the job, but the link should be something like this:

<li><a href="category.php?category=15">Cat1</a></li>

public function get_by_category () {
  $cat = $_GET['category']; //Check if is numeric, strip code out of it etc..
  $sql = $this->db->prepare("SELECT * FROM `table` WHERE `category` = $cat");
  $sql->bindParam(1, $cat);
  $sql->execute();

  while ($row = $sql->fetch()) {
    echo $row['Title'];
  }
}

除了mallix的答案外,如果类别是数字,我建议更改intval($ cat)上的$ cat;如果类别是字符串,则建议添加lashes($ cat)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM