-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsample.php
More file actions
114 lines (93 loc) · 2.66 KB
/
Copy pathsample.php
File metadata and controls
114 lines (93 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
function dbConnect(){
/*** connection credentials *******/
$servername = "localhost";
$username = "fakeAirbnbUser";
$password = "apples11Million!";
$database = "fakeAirbnb";
$dbport = 3306;
/****** connect to database **************/
try {
$db = new PDO("mysql:host=$servername;dbname=$database;charset=utf8mb4;port=$dbport", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
return $db;
}
/* query with no SQL arguments */
function getTwentyListings($db){
try {
$stmt = $db->prepare("select * from listings limit 20");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
catch (Exception $e) {
echo $e;
}
}
/* query with one SQL argument */
function getListingsBelowPrice($db, $price){
echo $num;
try {
$stmt = $db->prepare("select * from listings where price < ? order by price desc limit 20");
$data=array($price); //create an array of dynamic arguments, in the order they appear in the query
$stmt->execute($data);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (Exception $e) {
echo $e;
}
return $rows;
}
/* query with two SQL arguments */
function getListingsByNeighborhoodIdAndMaxPrice($db, $price, $neighborhoodId){
try {
$stmt = $db->prepare("select * from listings
join neighborhoods on neighborhoods.id=listings.neighborhoodId
where listings.price <= ? and neighborhoods.id = ?
order by listings.price desc
limit 5");
$data=array($price, $neighborhoodId); //array of arguments, in order
$stmt->execute($data);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (Exception $e) {
echo $e;
}
return $rows;
}
?>
<pre>
<code> <!-- this makes var_dump() easier to read-->
<?php
//get database connection
$db=dbConnect();
# 1.
//get 20 entries from listings table
//$rows=getTwentyListings($db);
//var_dump($rows);
# 2.
// get twenty entries from listings table below $price
//$price=150;
//$rows=getListingsBelowPrice($db, $price);
//var_dump($rows);
// get listings from neighborhood (given id) and max price (given price)
$neighborhoodId=22; //Eastmoreland
$price=100;
//$rows=getListingsByNeighborhoodIdAndMaxPrice($db, $neighborhoodId, $price);
/** see the resulting array **/
/*
var_dump($rows);
//loop through the rows:
foreach ($rows as $row){
$id=$row["id"];
$name=$row["name"];
$price=$row["price"];
echo "<p>id: $id, name: $name, price: $price</p>";
}
*/
?>
</code>
</pre>