I am brand new to PHP and mysql and am trying something here. In my HTML, I have one form where I enter a mileage and it’s passed on to the PHP code and converted to an integer. Then I want to take that and check against the database to isolate the record I want so I can do some computations. In other words, if the mileage entered (I save it in a veriable called $term) is less than or equal to a mileage in the table, I want to use the record that matches this criteria. For example, I enter 45 miles and the table has records at 40 miles and 50 miles, I want to pick the 50 mile level. If the user puts in 51, I want to use the 50 level. Things like that.
It connects to the database nicely but I’m not sure how to structure this at the foreach statement.
I have the following:
$term = (int)$_POST['term'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM rates WHERE mileage<=term";
foreach ($dbh->query($sql) as $row)
{
print $row['mileage'] .' - '. $row['ratepermile'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
When I do this, I get an invalid argument supplied foreach().
Then I started looking around and saw statements that look like this:
$stmt = $db->prepare( 'SELECT * FROM rates WHERE mileage<=:term' );
where the search parameter is passed and so on.
So now I’m confused about what the correct way is to select a single record in an ascending list of mileages in a database (the last matching record versus all that match) that satisfies a criteria or how to correctly structure the WHERE argument. Any suggestions?
Thank you for looking.
What you would need to do is use a
WHEREclause in combination withORDER BYandLIMITclauses. For example to get the highest value that is less than or equal to a given search criteria you would do:To get the lowest value that is greater than or equal to a given search value do:
As far as doing the actual PDO you would do something like this: