Saskarne ar MySQL datubāzi

Last modified by superadmin on 2018-01-12 20:38

Saskarne ar MySQL datubāzi

PHP ir iebūvēts atbalsts dažādām datubāzēm, t.sk. MySQL, tātad nevajag pat atsevišķu MySQL draiveri. Diemžēl, funkciju nosaukumi, lai strādātu ar šīm datubāzēm ir atšķirīgi. Programmētājam tas ir ērti, tomēr šādu kodu ir neērti pārnest uz citu servera platformu, kur ir cita datubāzu vadības sistēma.

<?
  $link = mysql_connect("localhost") or die ("Could not connect");
  print ("Connected successfully<br>");

  if (mysql_create_db("izvtesti")) {
      print ("Database created successfully<br>");
  } else {
      printf ("Error creating database: %s<br>", mysql_error());
  }

  if (mysql_select_db("demo",$link)) {
    print ("Changed database to 'demo'<br>");
  } else {
      printf ("Could not change to 'demo': %s<br>", mysql_error());
  }
 
  if (mysql_query("DROP TABLE IF EXISTS cilveks")) {
      print ("Dropped table 'cilveks'<br>");
  } else {
      printf ("Could not drop table: %s<br>", mysql_error());
  }

  if (mysql_query("CREATE TABLE cilveks (id INT, vards CHAR(25), uzvards CHAR(25));")) {
      print ("Created table 'cilveks'<br>");
  } else {
      printf ("Could not create table: %s<br>", mysql_error());
  }

  mysql_query("INSERT INTO cilveks (id,vards,uzvards) VALUES (1,\"George\",\"Bush\");")
      or die ("Invalid INSERT");

  mysql_query("INSERT INTO cilveks (id,vards,uzvards) VALUES (1,\"Dick\",\"Cheney\");")
      or die ("Invalid INSERT");

  $result = mysql_query("SELECT * FROM cilveks")
      or die ("Invalid SELECT");

  print "<table border>\n";
  while ($a = mysql_fetch_row($result)) {
      while (list($key,$value) = each($a)) {
          print "<tr><td>$key</td>"
 ."<td>$value</td></tr>\n";
      }
  }
  print "</table>\n";

  mysql_close ($link);
  print ("Closed connection");

?>
Tags:
Created by Kalvis Apsītis on 2008-05-03 16:02
    
This wiki is licensed under a Creative Commons 2.0 license
XWiki Enterprise 6.4 - Documentation