[Solved] How to check if a value exists in a database, then return the row of data


Your code has a few issues:

  1. Don’t mix more than one library. You are using mysql_ and mysqli_ together.
  2. Don’t use mysql_* functions. They are deprecated.
  3. No need of mysqli_close() function.
  4. You don’t need to repeat the table.
  5. You are not printing anything from the query’s result.

The problem with your code is, you need to change this line:

$result = mysqli_query($link, "SELECT * FROM `fixtureDetails` WHERE `sportID`='$sp'");

To populate as a table, use the resultset and loop.

if (mysqli_num_rows($result)) {
  while (false != ($data = mysqli_fetch_assoc($result))) {
    // Do whatever with your data.
    var_dump($data);
  }
} else {
  echo "No records.";
}

Final Code

<?php
  $link = mysqli_connect("localhost", "root", "pizza","fixtures");

  if ($_POST['SPORT'] == "Football") {
    $sp = '1';
  }
  if ($_POST['SPORT'] == "Tennis") {
    $sp = '2';
  }
  if ($_POST['SPORT'] == "Swimming") {
    $sp = '3';
  }

  // Execute the query and save the resultset.
  $result = mysqli_query($link, "SELECT * FROM `fixtureDetails` WHERE `sportID`='$sp'");
  // Check if there are any rows returned.
  if (mysqli_num_rows($result)) {
    // If there are rows returned, save every row to $data.
    while (false != ($data = mysqli_fetch_assoc($result))) {
      // Do whatever with your data.
      var_dump($data);
    }
  } else {
    // If there are no records, display a message.
    echo "No records.";
  }
?>

If you want a function to send the response of the count, you can have something like this:

<?php
  function getCount() {
    $link = mysqli_connect("localhost", "root", "pizza","fixtures");

    if ($_POST['SPORT'] == "Football") {
      $sp = '1';
    }
    if ($_POST['SPORT'] == "Tennis") {
      $sp = '2';
    }
    if ($_POST['SPORT'] == "Swimming") {
      $sp = '3';
    }

    // Execute the query and save the resultset.
    $result = mysqli_query($link, "SELECT * FROM `fixtureDetails` WHERE `sportID`='$sp'");
    // Check if there are any rows returned.
    return mysqli_num_rows($result);
  }
?>

If you want just a true or false, you can do:

<?php
  function getCount() {
    $link = mysqli_connect("localhost", "root", "pizza","fixtures");

    if ($_POST['SPORT'] == "Football") {
      $sp = '1';
    }
    if ($_POST['SPORT'] == "Tennis") {
      $sp = '2';
    }
    if ($_POST['SPORT'] == "Swimming") {
      $sp = '3';
    }

    // Execute the query and save the resultset.
    $result = mysqli_query($link, "SELECT * FROM `fixtureDetails` WHERE `sportID`='$sp'");
    // Check if there are any rows returned.
    return (mysqli_num_rows($result) > 0);
  }
?>

6

solved How to check if a value exists in a database, then return the row of data