Google search

Basic and advanced computer skills like Excel with macros, How to speed up your PC, C, CPP, Java programming, HTML, JavaScript, PHP, Wordpress, all web tools, Android tutorials, MySQL Tutorials, WAMP server installation. etc.

PHP-Database Programs

Following are the various PHP  programs to demonstrate Database  connections.

1. PHP Program to demonstrates whether the connection to mysql database is active or not.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'mars_db';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);

if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo 'Connected successfully';
}
?>

The above program will show following output.







2. PHP Program to create database from localhost.
<?php
$con=mysqli_connect("localhost","root","");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="CREATE DATABASE demo_12";

if (mysqli_query($con,$sql))
  {
  echo "Database demo_12 created successfully";
  }
else
  {
  echo "Error creating database: " . mysqli_error();
  }
?>

The above program produces following output.






3. PHP Program to create a table in database from localhost.
<?php
$con=mysqli_connect("localhost","root","","demo_12");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="CREATE TABLE emp_ret(FirstName CHAR(30),LastName CHAR(30),Age INT)";

if (mysqli_query($con,$sql))
  {
  echo "Table emp_ret created successfully";
  }
else
  {
  echo "Error creating table: " . mysqli_error();
  }
?>

The above program will have a following output.







4. PHP Program to connect MS Access Database using ODBC Data source. [Click here to create DSN (Data Source Naming) for MS Access.]
<html>
<body>
<h3 style="background-color:yellow"> Connecting to Ms 

Access Database using PHP </h3>
<hr>
<?php
$conn=odbc_connect('acc_php','','');
if (!$conn)
 {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM Cust";
$rs=odbc_exec($conn,$sql);

if (!$rs)
{
exit("Error in SQL");
}
echo "<table border=1><tr>";
echo "<th>Customer Code</th>";
echo "<th>Customer Name</th>";
echo "<th>Address</th></tr>";
while (odbc_fetch_row($rs))
  {
  $c_code=odbc_result($rs,"ccode");
  $c_name=odbc_result($rs,"cname");
  $c_addr=odbc_result($rs,"caddr");
  echo "<tr><td>$c_code</td>";
  echo "<td>$c_name</td>";
  echo "<td>$c_addr</td></tr>";
  }
odbc_close($conn);
echo "</table>";
?>
</body>
</html>

The above program produces following output.









That's all for now! for more PHP and MySQL programs click here

No comments:

Post a Comment