The power of FUNCTIONS in PHP

php_Function-min (1).png

Introduction

As a developer constantly developing web-based systems, I found myself repeating some aspects of my code, especially when selecting single data from multiple a database. For example, I could select a single row just to extract the name and last name.

$sql = "SELECT * FROM Users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}

The code above selects and returns multiple rows from a specified table, in this case, I am selecting the user's table, and from the user's table, I'm selecting all the fields. While there is no problem with the code above, I repeated the same code trying to select data from different tables.

This was a problem in need of a solution

In programming we have to avoid repeating code as much as possible, while is not a big problem, it is a good practice to avoid repeating code. So a function was a logical solution for me to solve this issue. The following shows an example of the function I created to solve this issue.

    function selectAllData($conn,$tableName,$dataToSelect,$dataSelectedIdOnTable,$dataSelectId){

        $sql = "SELECT $dataToSelect FROM $tableName WHERE $dataSelectedIdOnTable = '$dataSelectId'";
        $resultS = $conn->query($sql);

        if ($resultS->num_rows > 0) {
            while($row = $resultS->fetch_assoc()) {
                return $row[$dataToSelect];
            }
        } else {
            return false;
        }
    }

The function takes a number of parameters, this includes connection, table name, data you want to select, reference field, and reference data. In the Body of our function, we have to check if there is any data inside the table before we loop through the rows. Now if we do find some data! We have to return that data. Remember when we return a row, we have to specify the column in the row, by using the data u want to select passed as a parameter.

Application for this function

With this function, you can select data from multiple tables without repeating code. The following code will show you how this function is used. So basically what I'm doing is to check if a button has been clicked, and if# that is true I'm calling my function inside an if statement and I'm passing it the connection, the table name, the field I want to select. Because I want to select an email of a specific student, I need to pass the email filed as a reference and lastly pass in the data that is the email entered by the user. And I do the same thing with the password.

if(isset($_POST['btnLoginStudent'])){

    if(selectAllData($conn,'student','EMAIL','EMAIL',$_POST['email']) == $_POST['email'])
        //Check if the password exist
        if(selectAllData($conn,'student','PASSWORD','PASSWORD',$_POST['password']) == $_POST['password']){
            $_SESSION['email'] = $_POST['email'];
        }
        else{
            $errorLoginA = "";
        }
    }else{
        $errorLoginA = "";
    }
}

Second example

The following is another example of how to use this function. Again this is just a simple if statement checking if a teacher is offline or not. And note that I'm using the same function but selecting data from a different table.

    if(selectAllData($conn,'teacher','REGISTER_STATUS','EMAIL',$_SESSION['emailAdmin']) == 'Offline'){
        $locationActivateRegister = "";
    }else{
        $locationDeactivatedRegister = "";
    }

Conclution

I would love to hear your feedback on this article, please comment. and if you would like to know more about me you can visit my website

Did you find this article valuable?

Support Mohale Digital Media (PTY) LTD by becoming a sponsor. Any amount is appreciated!