recupero di dati da un'istruzione preparata
-
03-07-2019 - |
Domanda
Ho una funzione, che è quella di restituire una matrice di righe contenenti record da un database, selezionata in base a una query LIKE. Voglio che questa query sia una dichiarazione preparata per motivi di sicurezza. Apparentemente non posso usare i parametri associati e la funzione di query come sto facendo. Non sono sicuro, quindi, di come farmi interrogare come un'istruzione preparata e restituire le righe che sto cercando di restituire.
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);
}
}
Il ciclo while non è mai stato inserito affatto.
Soluzione
Anche se noioso se hai molte colonne, potresti semplicemente fare:
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);
}
}
Essenzialmente devi creare tu stesso l'array associativo richiesto, poiché non puoi usare $ result_set- > fetch_assoc ()
.
Altri suggerimenti
Scrivi " ... MI PIACE? ... "
(anziché " ... COME '%?%' ... "
) e $ getRecords- > bind_param (" s " ;, "% $ searchString% ");