Question

I have a function, which is to return an array of rows containg records from a database, selected based on a LIKE query. I want this query to be a prepared statement for security reasons. Apparently I can not use bound parameters and the query function as I am doing. I am unsure then, of how to keep me query as a prepared statement, and return the rows that I m trying to return.

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);
    }
}

The while loop is never entered at all.

Was it helpful?

Solution

Although tedious if you've got many columns, you could just do:

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);
    }
}

Essentially you have to create your required associative array yourself, since you can't use $result_set->fetch_assoc().

OTHER TIPS

Write "... LIKE ? ..." (rather than "... LIKE '%?%' ...") and $getRecords->bind_param("s", "%$searchString%");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top