Tuesday, March 10, 2015

Access to a MySQL Database with PHP

Note: The method presented here is unsafe and deprecated. I chose to explain it as an easy introduction, for real applications though the class mysqli should be used.

In today's post I want to show how one can access a MySQL database using PHP. How this can be done with C# is described on Udo's Blog.
In PHP this is pretty easy, there are many standard functions.
First we have to create a connection to the database, which we do as follows:

mysql_connect ("server address", "username", "password");

If the PHP script runs on the same server, on which also the database is located, "localhost" should work as server address.
After that we select the database we want to use (on a server there can be multiple databases):

mysql_select_db("database");

Via mysql_query we then can execute an arbitrary MySQL query, for example writing data to a table:

mysql_query("INSERT INTO Table(Rows) VALUES (Values);");

To read data we have to save the result of the query in a variable and then query the returned rows via mysql_fetch_object of this variable. Via x->Row we can access the content of column Row of x:

$query = mysql_query("SELECT Rows FROM Table WHERE condition;);
while($row = mysql_fetch_object($query))
   {
echo "$row->Row";
   }

For testing purposes I created a database on db4free.net, the database and the username are "csharptricks", the password is "12345678".
In this we have the table Customers, which contains the string columns FirstName and LastName. The following PHP script (http://bloggeroliver.bplaced.net/PHPExamples/mysql.php) adds a new line to the table, with the values given as POST parameters. Eventually every row from the table is returned:

<?php
mysql_connect ("db4free.net", "csharptricks", "12345678");
mysql_select_db("csharptricks");

$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];

mysql_query("INSERT INTO Customers (FirstName, LastName) VALUES ('$FirstName', '$LastName');");

$query = mysql_query("SELECT FirstName, LastName FROM Customers;");
while($row = mysql_fetch_object($query))
   {
          echo "$row->FirstName<br />";
          echo "$row->LastName<br />";
   }
?>

No comments:

Post a Comment