Exercise PHP - MySql - 1

7/10/13

PHP & MySql
PHP & MySql


Back again.
I suggest you learn about creating database and DML first , before take step in this post.


First you need to make connection to database and php file. The code is below :
<?php
$conn = mysql_connect("localhost","root","") or die("server down");
$db = mysql_select_db("inventory",$conn) or die("database dont exist");
?>


localhost is the name of the server, root is username and password is null. Save it as "connection.php"

Now we will show the data from table "goods".

First we need to connect the file with connection.php, and here's the code
include "connection.php";

Then we create some query to database and connect it with our connection.php


$sql = "select * from goods a,goods_type b where a.id_type = b.id_type";
$res = mysql_query($sql,$conn) or die(mysql_error());

Code above show that it will select all attributes from table goods and goods type, that have same id_type

The full code is here :

<?php 
include "connection.php";
$sql = "select * from goods a,goods_type b where a.id_type = b.id_type";
$res = mysql_query($sql,$conn) or die(mysql_error());
?>
<html>
<head>
</head>
<body>
<table border="1 " style='border-collapse:collapse;'>
<tr>
<th>Number</th>
<th>Code</th>
<th>Name</th>
<th>Stock</th>
<th>Price</th>
<th>Type</th>

</tr>
<?php
$i=1;
while ($data = mysql_fetch_array($res)){
if ($i%2==0) $bg='CCCCCC'; else $bg='FFFFFF';
echo "<tr bgcolor='".$bg."'>
<td>".$i."</td>
<td>".$data['code_goods']."</td>
<td>".$data['name_goods']."</td>
<td>".$data['stock_goods']."</td>
<td>".$data['price']."</td>
<td>".$data['name_type']."</td>

</tr>";
}
?>
</table>
</body>
</html>

On the logic side, inside the php code, we create variable $data to contain the attribut of Table goods and goods_type, so we just type the attribut name inside the array of variable $data.

Okay then, thanks again for reading my blog, hope this helpful.

No comments:

 

Tags