-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path86. PDOPrepSelectWithWhere2.php
More file actions
54 lines (40 loc) · 1.44 KB
/
86. PDOPrepSelectWithWhere2.php
File metadata and controls
54 lines (40 loc) · 1.44 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
<?php
// create variable for connection
$dsn = "mysql:host=localhost; dbname=test_db";
$db_user = "root";
$db_password = "";
// Create Connection with exception handling
try {
$conn = new PDO($dsn, $db_user, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected <br><hr>";
}
catch(PDOException $e) {
echo "Connection Failed " . $e->getMessage();
}
try{
// Using Positional Parameter
$sql = "SELECT * FROM student WHERE id = ?";
// $sql = "SELECT * FROM student WHERE id = ? && name=?";
// Using Named Parameter
// $sql = "SELECT * FROM student WHERE id = :id";
// $sql = "SELECT * FROM student WHERE id = :id && name= :name";
// Prepared Statement
$result = $conn->prepare($sql);
// Execute Prepared statement (Positional Paramter)
$result->execute([6]);
// $result->execute([6, 'Soni']);
// Execute Prepared statement (Named Paramter)
// $result->execute(array(':id' => 6));
// $result->execute(array(':id' => 6, ':name' => 'Soni'));
$row = $result->fetch(PDO::FETCH_ASSOC);
echo " ID: " . $row["id"] . " Name: " . $row["name"] . " Roll: " . $row["roll"] . " Address: " . $row["address"] . "<br><br>";
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Close Prepared Statement
unset($result);
// Close Connection
$conn = null;
?>