Isolate all of your new code and develop incrementally.
In a separate folder create a fresh connect.php
just echo a line and then include it in say, index.php
Make sure the echo appears.
Put a connection to your db in that and make sure it does not throw an error
echo 'No, I am NOT losing my mind.' . PHP_EOL ;
$user = 'rubble';
$pass = '';
try {
$PDO = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
So now you know you are at least connecting to your db.
in index.php, leave the function aside for a moment.
Just check you can get something from your db.
include './connect.php' ;
foreach($PDO->query('SELECT * FROM prices ORDER BY price DESC') as $row) {
print_r($row);
}
Bear in mind that probably the main benefit of using PDO is prepared statements which used correctly will protect your from sql injection attacks.
This means you are using 2 classes in tandem, PDO and PDOStatement. From my own experience of first using PDO not establishing which is which leads to much confusion and frustration.
That should give you a start, if all went well you have made a connection to PDO and used its native ->query() method to send in a query.
The next thing is to do what @perdeu; says and to pass that connection to a function.
include './connect.php' ;
function display_prices($PDO){
foreach($PDO->query('SELECT * FROM prices') as $row) {
print_r($row);
}
}
display_prices($PDO);
Then reintroduce your variable for the WHERE clause as a second argument and just stick it into the naked PDO connection for now.
display_prices($PDO, $region);
Then it would be a good idea to introduce the PDOStatement so that you properly escape the data
function display_prices($PDO, $region) {
$stmt = $PDO->prepare("SELECT * FROM prices where region = ?");
// now you've switched to using PDOStatement class ...
// this is just one way of doing it, taken from the manual
if ($stmt->execute(array($region))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
Then you can fiddle with that and you should try using bindparam() method etc.
Just to say I haven’t tested any of this code btw - so there might be syntax errors etc but should get you started. See how you get on.