Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $db_host = "localhost";
- $db_name = "your_database_name";
- $db_user = "your_database_user";
- $db_pass = "your_database_pass";
- /* function to run a SQL query using PDO connection to MySQL db */
- function sql($s,$v=array()){
- global $db_host, $db_name, $db_user, $db_pass;
- $dbh = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);
- if (!$dbh) die("Could not connect to database");
- $stmt = $dbh->prepare($s);
- if (!$stmt) die("Prepare failed");
- foreach($v as $key => $val) $bind = $stmt->bindValue($key,strval($val));
- $exec = $stmt->execute();
- if (!$exec) die("Execute failed");
- $dbh = null;
- return $stmt;
- }
- /* function to print out a record set as an HTML table */
- function html_table($s){
- echo "<table border=1><tr>";
- for($i=0;$i<$s->columnCount();$i++) echo "<th>".$s->getColumnMeta($i)["name"]."</th>";
- echo "</tr>";
- while($r=$s->fetch(PDO::FETCH_ASSOC)) {
- echo "<tr>";
- foreach($r as $val) echo "<td>$val</td>";
- echo "</tr>";
- }
- echo "<table>";
- }
- ?>
- <!DOCTYPE html>
- <html>
- <body>
- <?php
- /* create a table */
- $q = "create table tbl_users (usr_id int, usr_name varchar(16))";
- $s = sql($q);
- /* insert a record */
- $q = "insert into tbl_users (usr_id, usr_name) values (:b_id, :b_nme)";
- $s = sql($q, array(":b_id"=>1,":b_nme"=>"John Smith"));
- /* print the table */
- $q = "select * from tbl_users";
- $s = sql($q);
- html_table($s);
- /* drop the table */
- $q = "drop table tbl_users";
- $q = sql($q);
- ?>
- </body>
- </html>
Add Comment
Please, Sign In to add comment