Sunday, July 1, 2012

PHP Database Access


Create the database in MySQL



PHP with databases access, we have chosen MySQL database because it is free and also because it is the most widely used in UNIX environment. To this end, the server where the pages are hosted must provide us with tools to create the database or have access to Telnet.
The command to create a MySQL database is the following: mysqladmin -u root create data_base

To create the table you can use your web server's MySQL administration tool or you can write a text file with the content of the equivalent SQL and then indicate the database engine to execute it with the following instruction: mysql -u root base_datos <test.sql

Connection to the database


<html> 
<head> 
   <title>PHP SWT Example</title> 
</head> 
<body> 
<?php
function Connect()
{
   if (!($link=mysql_connect("localhost","root","")))
   {
      echo "Error connecting to server.";
      exit();
   }
   if (!mysql_select_db("base_datos",$link))
   {
      echo "Error Selecting database.";
      exit();
   }
   return $link;
}

$link=Conectarse();
echo "Connection Success.<br>";

mysql_close($link); //cierra la conexion
?>
 
</body> 
</html> 


Querying the database


<?php 
function Connect() 

   if (!($link=mysql_connect("localhost","root",""))) 
   { 
       echo "Error connecting to server.";   
      exit(); 
   } 
   if (!mysql_select_db("base_datos",$link)) 
   { 
       echo "Error Selecting database.";  
       exit(); 
   } 
   return $link; 

?>


<html> 
<head> 
   <title>PHP SWT Example</title> 
</head> 
<body> 
<H1>Ejemplo de uso de bases de datos con PHP y MySQL</H1> 
<?php
   include("connection.phtml");
   $link=Conect();
   $result=mysql_query("select * from users",$link);
?>
 
   <TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1> 
      <TR><TD>&nbsp;ID</TD><TD>&nbsp;Username&nbsp;</TD></TR> 
<?php     

   while($row = mysql_fetch_array($result)) {
      printf("<tr><td>&nbsp;%s</td><td>&nbsp;%s&nbsp;</td></tr>", $row["id"],$row["username"]);
   }
   mysql_free_result($result);
   mysql_close($link);
?>
 
</table> 
</body> 
</html> 


Inserting records to the database


<?php
   include("connection.phtml");
   $link=Conect();
   $id=$_GET['id'];
   $username=$_GET['username'];  
   mysql_query("insert into users(id,username) values ('$id','$username')",$link);
  
   header("Location: thanks.phtml");
?>
 




No comments:

Post a Comment

There was an error in this gadget