MySQL request return null Controller PHP


I’ve create a table order on my code, My idea is to generate an Unique order Id per user.

On my controller I have a code with the MYSQL request, and a function to return the result (which works on other SQL requests).

So My idea is on MySQL request is to count the number of order with the same number and If result is =1 I have to generate a new order number. On my order class I have this function:

    public static function getCountOrderIfExist($bdd, $order_number) {
    $requete = "SELECT * FROM Order WHERE order_number='$order_number'";
    $commandes = getResultatRequete($bdd, $requete);
    return !empty($commandes) ? $commandes : null;

And I call it on my Controller:

$count = Order::getCountOrderIfExist($bdd, $order_number);
                        while ($count >= 1) {
                            $order_number= $user_role."_".$user->getUtilisateurId().rand(1,99999)."_".$user->getEntreprise()->getId().rand(1,999999);

And here is the code of my getResultatRequete:

function getResultatsRequete(PDO $bdd, $requete) {
    $reponse_requete = $bdd->query($requete);
    if ($reponse_requete != false) {
        $resultat_requete = $reponse_requete->fetchAll();
        return str_replace("\\", "", $resultat_requete);
    } else {
        printErrorInfo($bdd, $requete, true);
        return array();

When I run my code on debug mode the SQL request return NULL and I don’t understand why, because when I run my Request on a terminal it works well. Any idea?


From our correspondence in the comments, it seems that the problem lies in the return statement:

return !empty($commandes) ? $commandes : null;

That statement returns any found records, or null if no records are found. However, it seems that the controller expects the function to return the number of matching records (0 if none are found).

In order to return a number for you to work with, you need to instead do a count of the returned records:

return count($commandes);

This should give you the results you need.

Answered By – Fabian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published