Question

J'ai une fonction qui consiste à renvoyer un tableau de lignes contenant des enregistrements d'une base de données, sélectionnés en fonction d'une requête LIKE. Je souhaite que cette requête soit une instruction préparée pour des raisons de sécurité. Apparemment, je ne peux pas utiliser les paramètres liés et la fonction de requête comme je le fais. Dans ce cas, je ne sais pas trop comment conserver ma requête en tant qu’instruction préparée et renvoyer les lignes que j’essaie de renvoyer.

function getRowsByArticleSearch($searchString, $table, $max) {
    $con = mysqli_connect("localhost", "x", "x", "x");
    //global $con;
    $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
    if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        //$getRecords->execute();
        echo "test if";
        //$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
        while ($getRecords->fetch()) {
            $result = $con->query($recordsQuery);
            $rows = array();
            echo "test while";
            while($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
        }
        return $rows;
    } else {
        print_r($con->error);
    }
}

La boucle while n'est jamais entrée.

Était-ce utile?

La solution

Bien que fastidieux si vous avez plusieurs colonnes, vous pouvez simplement faire:

function getRowsByArticleSearch($searchString, $table, $max) {

  $con = mysqli_connect("localhost", "x", "x", "x");
  $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE ? ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
  if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        $getRecords->execute();
        $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
        $rows = array();
        while ($getRecords->fetch()) {
            $row = array(
                'ARTICLE_NO' => $ARTICLE_NO,
                'USERNAME' => $USERNAME,
                 ...
            );
             $rows[] = $row;
        }
        return $rows;
    } else {
        print_r($con->error);
    }
}

En gros, vous devez créer vous-même le tableau associatif requis, car vous ne pouvez pas utiliser $ result_set- > fetch_assoc () .

Autres conseils

Écrivez & ...; LIKE? ... " (plutôt que "... LIKE '%?%' ..." " ) et $ getRecords- > bind_param (" s " ;, "% $ searchString% ");

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top