nsilva
nsilva

Reputation: 5614

PHP / MySql / Variable loop?

I have the following code which checks for a 'Fixed Fare' using the first 5 characters of a postcode from A to B.

So if LE675FE is input, $full_post_code_a = LE675F;

Basically I am wanting to do is a loop that will check the database using the first 4, and 3 characters, so $full_post_code_a = LE675F / LE675 and LE67

Just wondering how it would be possible to do this?

private static function checkFixedFarePC($post_codes) {

    self::$arr_postcodes = explode(",", $post_codes);

    // Get full postcode of Pickup

    $full_post_code_a = (self::$arr_postcodes[0]);

    // Get full postcode of Destination

    $full_post_code_b = (self::$arr_postcodes[1]);

    // Get first 5 characters of pickup & destination postcode

    $post_code_a = substr($full_post_code_a,0 ,5);

    $post_code_b = substr($full_post_code_b,0 ,5);

    // Pass postcodes to check if a fixed fare is possible

    return self::getFixedFare($post_code_a, $post_code_b);

}

Which gets sent to the following funciton:

private static function getFixedFare($post_code_a, $post_code_b) {

$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

try {

    $query =   "SELECT VehicleSystemId, Fare FROM tblfixedfares
                WHERE ShortPostCodeA = '$post_code_a'
                AND ShortPostCodeB = '$post_code_b'
                AND DayHalf = :day_half
                AND VehicleSystemId IN ('Car', '6B')";

    $stmt = $dbh->prepare($query);

    $stmt->bindParam(':day_half', self::$day_half, PDO::PARAM_STR);

    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);

    $stmt->closeCursor();

    $dbh = null;

    return $result;

}

catch (PDOException $pe) {
    die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}

Any help would be much appreciated!

Upvotes: 0

Views: 132

Answers (2)

v0d1ch
v0d1ch

Reputation: 2748

 WHERE 
 ShortPostCodeA IN 
 ('{$post_code_a}','{$post_code_b}')

Upvotes: 0

nsilva
nsilva

Reputation: 5614

I just thought, I could do:

$post_code_c = substr($full_post_code_a,0 ,4);
$post_code_d = substr($full_post_code_a,0 ,3);

Then pass these to the query: return self::getFixedFare($post_code_a, $post_code_b, $post_code_c);

and then change the query to:

WHERE ShortPostCodeA = '$post_code_a' OR ShortPostCodeA = '$post_code_c' OR ShortPostCodeA = '$post_code_d

Although there may be a better way of doing this...

Upvotes: 1

Related Questions