Pages

Monday, 16 February 2015

Integrating PHP with Embedded System : Chapter -6

How to connect to MYSQL database using PHP

To connect MYSQL using PHP go tohttp://localhost//phpmyadmin
Enter the username and password
Give the database name in the field ‘create new database’


  Click on create button

   Create a new table in the database by giving a table name and number of fields then click on Go


      To give field name to the created table, write the field name in the ‘field’ column, select the data types for each fields, specify the length of each field then click on save to save the fields and click on Go

      When clicked on Go the table field details will be displayed



    To insert values in the field, go to insert and enter the values. Then click on Go
     To view the created table, go to browse
     To insert values in the field, go to insert and enter the values. Then click on Go

     To view the created table, go to browse.


    To insert the values, go to SQL and write the query to insert the values and click on Go

    SQL query for insert:


    Syntax:
                    Insert into table_name values(‘value1’,’value2’,…);
    Example:
                   Insert into Login values(‘Radha’,’hello’);


       To update the values, go to SQL and write the query to update the values and click on Go
       SQL query for update:
                  Syntax:
                               Update table_name set field_name=’value’ where field_name=’value’;
              Example:
                                Update Login set password=’abcde’ where name=’Radha’;

    To delete the values, go to SQL and write the query to delete the values and click on go

       SQL query for delete:
                              Syntax:
                                          Delete from table_name where field_name=’value’;
                          Example:
                                          Delete from Login where name=’Radha’;
               
               

  The functions used to connect web form to the MYSQL database: 


    mysql_connect():         
            This function opens a link to a MySQL server on the specified host (in this case it's localhost)along with a username (root) and password(q1w2e3r4/). The result of the connection is stored in  the variable $db.
    mysql_select_db():
               This tells PHP that any queries we make are against the mydb database.

     mysql_query():
                Using the database connection identifier, it sends a line of SQL to the MySQL server to be processed. The results that are returned are stored in the variable $result.

      mysql_result():
                  This is used to display the values of fields from our query. Using $result, we go to the first row, which is numbered 0, and display the value of the specified fields.

       mysql_result($result,0,"position")):
                     This should be treated as a string and printed.

       

  Display the data from MYSQL database in web   form


    <html>
    <body>
      < ?php
     //Open MYSQL server connection 
     $db = mysql_connect("localhost", "root","q1w2e3r4/");
     //Select the databaseusingMYSQL server connection
     mysql_select_db("mydb",$db);
          /*Using the database connection identifier, it sends
a line of SQL to the MySQL server to be processed
     and theresults are stored in the variable
  $result. */
$result = mysql_query("SELECT * FROM employees",$db);
      //Displaying the details in a table
     echo "<table border=1>";
     echo "<tr><th>Name</th><th>Position</th></tr>";
     while ($myrow = mysql_fetch_row($result)) {
          printf("<tr><td>%s %s</td><td>%s</td></tr>",
          $myrow[1], $myrow[2],$myrow[4]);
}
echo "</table>";
? ?>
   </body>
    </html>

    OUTPUT of the above given Example would be:
   

                                 
     

 Insert the data into MYSQL database using web form

       <html>
  <body>
   <?php
   if ($submit) {
     //Open MYSQL server connection
     $db = mysql_connect("localhost", "root","q1w2e3r4/");
     //Select the database using MYSQL server connection
         mysql_select_db("mydb",$db);
     /*Write insert query and assign the query in $sql
Variable*/
     $sql = "INSERT INTO employees (first,last,address,position)
     VALUES('$first','$last','$address','$position')";
//Execute the query
$result = mysql_query($sql);
echo "Thank you! Information entered.";
}
   else
{
//display form
  ?>
<form method="post" action="<?php echo $PHP_SELF?>">
First name:<input type="Text" name="first"><br>
Last name:<input type="Text" name="last"><br>
Address:<input type="Text" name="address"><br>
Position:<input type="Text" name="position"><br>
<input type="Submit" name="submit" value="Enter
 information">
</form>
      <?php
    }// end if
  ?>
   </body>
   </html>
      
              OUTPUT of the above given Example would be:
        

 Update the data present in MYSQL database using web form

  <html>
 <body>
 <?php
   //Open MYSQL server connection
  $db = mysql_connect("localhost", "root","q1w2e3r4/");
  //Select the database using MYSQL server connection
  mysql_select_db("mydb",$db);
  if ($id) {
  if ($submit) {
     //Write UPDATE query and assign to $sqlVariable  
    $sql = "UPDATE employees SET
           first='$first',last='$last',
                address='$address',
   position='$position'
                 WHERE id=$id";
           //Execute the query
           $result = mysql_query($sql);
     echo "Thank you! Information updated.";
}
else
{

           //Write query to SELECT data from table
           $sql = "SELECT * FROM employees WHERE id=$id";
           //Execute the query
           $result = mysql_query($sql);
           //Fetch the values
           $myrow = mysql_fetch_array($result);
  ?>
<form method="post" action="<?php echo $PHP_SELF?>">
     <input type=hidden name="id" value="<?php echo
  $myrow["id"] ?>">
First name:<input type="Text" name="first"
   value="<?php echo $myrow["first"] ?>"><br>
Last name:<input type="Text" name="last"
  value="<?php echo $myrow["last"] ?>"><br>
Address:<input type="Text" name="address"
  value="<?php echo $myrow["address"]?>"><br>
Position:<input type="Text" name="position"
   value="<?php echo $myrow["position"]?>"><br>
<input type="Submit" name="submit" value="Enter
    information">
</form>
 <?php
      }
  }  
  else
{
  //display list of employees
   $result = mysql_query("SELECT * FROM employees",$db);
   while ($myrow = mysql_fetch_array($result)) {
   printf("<a href=\"%s?id=%s\">%s %s</a><br>",
    $PHP_SELF, $myrow["id"],$myrow["first"],
    $myrow["last"]);
    }
    }
  ?>

 </body>
 </html>
   
     OUTPUT of the above given Example would be:
     

 Delete the data from MYSQL database using web form 


 <html>

 <body> 

 <?php

//Open MYSQL server connection
  $db = mysql_connect("localhost", "root","q1w2e3r4/");
 //Select the database using MYSQL server connection 
  mysql_select_db("mydb",$db);
 if ($id) {
 if ($submit) {
     //Write DELETE query to delete data from table based on ID
  $sql = "DELETE FROM employees WHERE id=$id"; 
//Execute the query
  $result = mysql_query($sql);
echo "Thank you! Information deleted.";
}
  else
{
 //Write SELECT query to select data from table based on ID
  $sql = "SELECT * FROM employees WHERE id=$id";
  $result = mysql_query($sql);
$  myrow = mysql_fetch_array($result);
  ?>
  <form method="post" action="<?php echo $PHP_SELF?>">
  <input type=hidden name="id"
           value="<?php echo $myrow["id"] ?>">
     First name:<input type="Text" name="first"
readonly="readonly"
     value="<?php echo $myrow["first"] ?>"><br>
  Last name:<input type="Text" name="last"
     readonly="readonly"
value="<?php echo $myrow["last"] ?>"><br>
Address:<input type="Text" name="address"
     readonly="readonly"
     value="<?php echo $myrow["address"]?>"><br>
Position:<input type="Text" name="position"
     value="<?php echo $myrow["position"]?>"><br>
<input type="Submit" name="submit"
     value="Delete information">
  </form>
  <?php  

  }
}}
  else 
{ //display list of employees
  $result = mysql_query("SELECT * FROM
  employees",$db);
  while ($myrow = mysql_fetch_array($result)) {
  printf("<a href=\"%s?id=%s\">%s %s</a><br>",
  $PHP_SELF, $myrow["id"],$myrow["first"],
  $myrow["last"]);
       }
  } 
 ?>
 </body>
 </html>

       OUTPUT of the above given Example would be:
                                 
          

 









    








                                



       






Sunday, 15 February 2015

Integrating PHP with Embedded System : Chapter -5

The $_ POST Function Example

form1.html


<html>
   <body>   
        /* form submitted using ‘post’ method, action specifies
        next page which is to be loaded when button is clicked*/
        <form action="welcome1.php" method="post">
                   // textbox is to take user input
             Name: <input type="text" name="fname" />
             Age: <input type="text" name="age" />
             // Submit button is to submit the value to next page
             <input type="submit" />
        </form>
   </body>
</html>


welcome1.php
<html>
   <body>
                // $_GET to receive the data sent from form1.html
        Welcome <?php echo $_POST["fname"]; ?>.<br />
        You are <?php echo $_POST["age"]; ?> years old!
   </body>
</html>

OUTPUT of the above given Example is as follows:
In this example, when you click on the “submit” button, the values will not be displayed the query string portion of the URL.

Another Example for PHP form

Form.html


<html>

<head>

<title>Process the HTML form data with the POST

method</title>

</head>

<body>

/* form submitted using ‘post’ method, action specifies next page which is to be loaded when button is clicked*/

<form name="myform" action="process.php" method="POST">



//create an hidden textbox

<input type="hidden" name="check_submit" value="1" />



// textbox is to take user input

     Name: <input type="text" name="Name" /><br />

Password: <input type="password" name="Password"

maxlength="10" /><br />



     // Use ‘select’ tag to display the various options

Select something from the list: <selectname="Seasons">

<option value="Spring"

selected="selected">Spring</option>

<option value="Summer">Summer</option>

<option value="Autumn">Autumn</option>
<option value="Winter">Winter</option>
</select><br /><br />

Choose one: 
//This will create radio buttons
<input type="radio" name="Country" value="USA" /> USA
<input type="radio" name="Country" value="Canada" />
     Canada
<input type="radio" name="Country" value="Other" />
Other
<br />
Choose the colors:
//This will create checkbox
<input type="checkbox" name="Colors[]" value="green"
checked="checked" /> Green
<input type="checkbox" name="Colors[]" value="yellow"
/> Yellow
<input type="checkbox" name="Colors[]" value="red" />

 Red 
<input type="checkbox" name="Colors[]" value="gray" />
 Gray
<br />

   // Submit button is to submit the value to next page
<input type="submit" />
</form>
</body>
</html>


Process.php

<html>
<body>
<?php
   if (array_key_exists('check_submit', $_POST)) {
/*Converts the new line characters (\n) in the text
area into HTML line breaks (the <br /> tag)*/
    $_POST['Comments'] = nl2br($_POST['Comments']); 
//Check whether a $_GET['Languages'] is set
   if ( isset($_POST['Colors']) ) { 
    $_POST['Colors'] = implode(', ', $_POST['Colors']);
//Converts an array into a single string
   }

//Let's now print out the received values in thebrowser
   echo "Your name: {$_POST['Name']}<br />";
   echo "Your password: {$_POST['Password']}<br />";
   echo "Your favourite season: {$_POST['Seasons']}
<br/><br />";
   echo "You are from: {$_POST['Country']}<br />";
   echo "Colors you chose: {$_POST['Colors']}<br />";
  }
else
  {
echo "You can't see this page without submitting the
form.";
}
?>
</body>
</html>


OUTPUT of the above given Example is as follows:
Date() and time() function in PHP
  • The PHP date() function formats a timestamp to a more readable date             and  time.
  • A timestamp is a sequence of characters, denoting the date and/or                   time at which a certain event occurred.
  •  Some characters that are commonly used for date and time:
                                ·        d - Represents the day of the month (01 to 31)
              ·        m - Represents a month (01 to 12)
              ·        Y - Represents a year (in four digits)
              ·        l (lowercase 'L') - Represents the day of the week
              ·        h - 12-hour format of an hour with leading zeros (01 to 12)
              ·        i - Minutes with leading zeros (00 to 59)
              ·        s - Seconds with leading zeros (00 to 59)
              ·        a - Lowercase Ante meridiem and Post meridiem (am or pm)         

Example

<html>

   <body>
        <?php

             // display the date in the format YYYY/MM/DD
             echo "Today is " . date("Y/m/d") . "<br>";
             // ‘l’ is used to display the day
             echo "Today is " . date("l"). "<br>";
             // display the time in the format HH:MM:SS
             echo "The time is " . date("h:i:sa");

        ?>
   </body>
</html>
OUTPUT of the above given Example is as follows:

Today is 2014/08/19
            Today is Tuesday

The time is 12:23:22am