ලේසියෙන්ම හොයාගන්න මෙතනින්

PHP, MySQL Integration - Perform Select, Insert, Update, Delete from PHP

In order to MVC Architecture, try to keep you coded php files seperately and try to reduce repeat save code. A simple basic programming concept. However to get establish database connection in PHP is very simple. Write a seperate php file for prepare database connection. In my case, my file name is db.php which I put it in controller folder.

<?php
    $host="localhost";
    $userName="root";
    $password="yourPassword";
    $db_name="databaseName";
    mysql_connect($host,$userName,$password) or die("Unable To Connect Database");
    mysql_select_db("$db_name") or die ("No Such Database.");

?>

You just need to change bold letters only. Most of the time mysql password and database name only.
Red Text two lines are the most important. mysql_connect method will get 3 parameters and will establish Database connection for you. mysql_select_db method will be select database to be used. Thats all.


Then lets see how to retrieve data from database.
<?php
        $sql = mysql_query("select column1,column2,column3 from anyTable"); // your query
        $existCount = mysql_num_rows($sql); // this how you can get row count
        while($row = mysql_fetch_array($sql)){ // read Results till end
                $column1= $row["
column1"];  // assign current result row, column 1 value to a variable
                $
column2= $row["column2"];
                $
column3= $row["column3"];                echo $column1; // print $column1 variable value
                echo $column2;         
                echo $column3;            
       }
?>

Then lets see how to insert/update/delete data to database.
<?php
$querry = "INSERT INTO anyTable(column1,column2,column3) VALUES ('1','Value1','Value2')";
$result = mysql_query($querry);
if ($result == 1) {
        echo "<script type='text/javascript'>alert('Executed Success.');</script>";
} else {
        echo "<script type='text/javascript'>alert('Execution Failed.')</script>";
}
?>
Above example shows only for insert query. Same coding to update, delete fuctions. Only the SQL query will be changed.

No comments :

Post a Comment