home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / db_operation.iso / PDO_2 / db_operation.php
Encoding:
PHP Script  |  2016-01-01  |  2.3 KB  |  85 lines

  1. <?php
  2. // ╟ß╟╩╒╟ß π┌ π╧φ╤ ▐µ╟┌╧ ╟ß╚φ╟Σ╟╩
  3. $servername = "localhost";
  4. $username = "root";
  5. $password = "";
  6.  
  7. try {
  8.   $conn = new PDO("mysql:host=$servername", $username, $password);
  9.   // set the PDO error mode to exception
  10.   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  11.   $sql = "CREATE DATABASE t001";
  12.   // use exec() because no results are returned
  13.   $conn->exec($sql);
  14.   echo "Database created successfully<br>";
  15. } catch(PDOException $e) {
  16.   echo $sql . "<br>" . $e->getMessage();
  17. }
  18.  
  19. // ┼Σ╘╟┴ ╠╧µß
  20. $dbname = 't001';
  21. try {
  22.   $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  23.   // set the PDO error mode to exception
  24.   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  25.  
  26.   // sql to create table
  27.   $sql = "CREATE TABLE  `table1` (
  28.     `id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  29.     `col1` VARCHAR( 124 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ,
  30.     `col2` TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
  31.     ) ENGINE = MYISAM ;";
  32.  
  33.   // use exec() because no results are returned
  34.   $conn->exec($sql);
  35.   echo "Table table1 created successfully<br>";
  36. } catch(PDOException $e) {
  37.   echo $sql . "<br>" . $e->getMessage();
  38. }
  39.  
  40. // ╟╧╬╟ß ╙╪╤φΣ πΣ ╟ß╚φ╟Σ╟╩
  41. try {
  42.   $sql = "INSERT INTO `table1` (`id`, `col1`, `col2`) VALUES
  43.         (NULL, 'Ahmed', 'He is a teacher.'),
  44.         (NULL, 'Ali', 'He is a doctor.');";
  45.   // use exec() because no results are returned
  46.   $conn->exec($sql);
  47.   echo "New 2 records created successfully<br>";
  48. } catch(PDOException $e) {
  49.   echo $sql . "<br>" . $e->getMessage();
  50. }
  51.  
  52. // ╟▌╤╟█ ╠╧µß
  53. try {
  54.   $sql = "TRUNCATE TABLE `table1`;";
  55.   // use exec() because no results are returned
  56.   $conn->exec($sql);
  57.   echo "TRUNCATE table successfully<br>";
  58. } catch(PDOException $e) {
  59.   echo $sql . "<br>" . $e->getMessage();
  60. }
  61.  
  62. // ═╨▌ ╠╧µß
  63. try {
  64.   $sql = "DROP TABLE `table1`;";
  65.   // use exec() because no results are returned
  66.   $conn->exec($sql);
  67.   echo "DROP TABLE successfully<br>";
  68. } catch(PDOException $e) {
  69.   echo $sql . "<br>" . $e->getMessage();
  70. }
  71.  
  72. // ═╨▌ ▐╟┌╧╔ ╚φ╟Σ╟╩
  73. try {
  74.   $sql = "DROP DATABASE  `t001`;";
  75.   // use exec() because no results are returned
  76.   $conn->exec($sql);
  77.   echo "DROP DATABASE successfully<br>";
  78. } catch(PDOException $e) {
  79.   echo $sql . "<br>" . $e->getMessage();
  80. }
  81.  
  82. $conn = null;
  83. ?>
  84.  
  85.