1

How to fix the function error?

Deprecated: Required parameter $orderfield follows optional parameter $where in C:\xampp\htdocs\shop\includes\functions\functions.php on line 8

function getAllFrom($field, $table, $where = NULL, $and = NULL, $orderfield, $ordering = "DESC") {
    global $con;
    $getAll = $con->prepare("SELECT $field FROM $table $where $and ORDER BY $orderfield $ordering");
    $getAll->execute();
    $all = $getAll->fetchAll();
    return $all;
}
<?php
$allItems = getAllFrom('*', 'items', 'where Approve = 1', '', 'Item_ID');
foreach ($allItems as $item) {
    echo '<div class="col-sm-6 col-md-3">';
    echo '<div class="thumbnail item-box">';
    echo '<span class="price-tag">$' . $item['Price'] . '</span>';
    echo '<img class="img-responsive" src="img.png" alt="" />';
    echo '<div class="caption">';
    echo '<h3><a href="items.php?itemid='. $item['Item_ID'] .'">' . $item['Name'] .'</a></h3>';
    echo '<p>' . $item['Description'] . '</p>';
    echo '<div class="date">' . $item['Add_Date'] . '</div>';
    echo '</div>';
    echo '</div>';
    echo '</div>';
}
?>
ecm
  • 2,583
  • 4
  • 21
  • 29
Yasir ayad
  • 59
  • 1
  • 1
  • 9
  • 1
    Maybe give the variable `orderfield` a value like `$orderfield = ''`. But to be honest, querying your database like this feels very wrong – Baracuda078 Aug 20 '21 at 13:00

1 Answers1

5

Your function has required paramaters after optional ones...

getAllFrom($field, $table, $where = NULL, $and = NULL, $orderfield, $ordering = "DESC")

$where $and are both optional (because they have default values). $orderfield is required because it doesn't have a default value.

So the order should be:

getAllFrom($field, $table, $orderfield, $where = NULL, $and = NULL, $ordering = "DESC")

Order make $where and $and required too...

getAllFrom($field, $table, $where, $and, $orderfield, $ordering = "DESC")

If you need a "non-breaking" solution you could do something like...

function getAllFrom($field, $table, $where = NULL, $and = NULL, $orderfield = null, $ordering = "DESC") {

    if ( $orderfield === null ) {
        throw new InvalidArgumentException( 'Parameter 5 of getAllFrom function is required.' );
    }

    global $con;

    $getAll = $con->prepare("SELECT $field FROM $table $where $and ORDER BY $orderfield $ordering");

    $getAll->execute();

    $all = $getAll->fetchAll();

    return $all;

}
Levi Cole
  • 3,561
  • 1
  • 21
  • 36