-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathread.php
More file actions
99 lines (80 loc) · 2.53 KB
/
read.php
File metadata and controls
99 lines (80 loc) · 2.53 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
<!DOCTYPE HTML>
<html>
<head>
<title>PDO Read Records - code from codeofaninja.com</title>
</head>
<body>
<!-- just a header label -->
<h1>PDO: Read Records</h1>
<?php
// include database connection
include 'database.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
// if it was redirected from delete.php
if($action=='deleted'){
echo "<div>Record was deleted.</div>";
}
// select all data
$query = "SELECT id, name, description, price FROM products";
$stmt = $con->prepare($query);
$stmt->execute();
// this is how to get number of rows returned
$num = $stmt->rowCount();
// link to create record form
echo "<div>";
echo "<a href='create.php'>Create New Record</a>";
echo "</div>";
//check if more than 0 record found
if($num>0){
echo "<table>";//start table
//creating our table heading
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Description</th>";
echo "<th>Price</th>";
echo "<th>Action</th>";
echo "</tr>";
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row['firstname'] to
// just $firstname only
extract($row);
// creating new table row per record
echo "<tr>";
echo "<td>{$id}</td>";
echo "<td>{$name}</td>";
echo "<td>{$description}</td>";
echo "<td>${$price}</td>";
echo "<td>";
// we will use this links on next part of this post
echo "<a href='update.php?id={$id}'>Edit</a>";
echo " / ";
// we will use this links on next part of this post
echo "<a href='#' onclick='delete_user({$id});'>Delete</a>";
echo "</td>";
echo "</tr>";
}
// end table
echo "</table>";
}
// if no records found
else{
echo "<div>No records found.</div>";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if (answer){
// if user clicked ok,
// pass the id to delete.php and execute the delete query
window.location = 'delete.php?id=' + id;
}
}
</script>
</body>
</html>