Tuesday, 15 October 2024

logout.php

 Hi all

use this code


<?php



session_start();

unset($_SESSION['username']);

header('location:index.php');


?>

user home page

 Hi all


Use this code

//userhome.php

<!DOCTYPE html>

<html lang="en">

<?php

session_start();

echo 'Welcome '.$_SESSION['username'];

if(!isset($_SESSION['username']))

{

header('location:index.php');

}



?>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>User Home</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            background-color: #f4f4f4;

            margin: 0;

            padding: 0;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

        }

        .container {

            text-align: center;

            background-color: #fff;

            padding: 30px;

            border-radius: 8px;

            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

        }

        h1 {

            color: #333;

        }

        a {

            display: inline-block;

            margin: 10px;

            padding: 10px 20px;

            background-color: #007BFF;

            color: #fff;

            text-decoration: none;

            border-radius: 4px;

            transition: background-color 0.3s ease;

        }

        a:hover {

            background-color: #0056b3;

        }

    </style>

</head>

<body>


<div class="container">

    <h1>Welcome to User Home</h1>

    <p>Please select an option:</p>

    <a href="profile.php">Go to Profile</a>

    <a href="settings.php">Go to Settings</a>

<a href="viewpatient.php">View Patients</a>

<a href="logout.php">Logout</a>

</div>


</body>

</html>


Mysqli Login

 Hi all,

Use this code

<?php


$username = $_POST['username'];

$password = $_POST['password'];


$count1 = substr_count($username, "'");

$count2 = substr_count($password, "'");

$err = 0;


if ($count1 > 0 || $count2 > 0) {

    $err = 1;

}


// Create connection using MySQLi

include('dbconnect.php');


if (!$con) {

    die('Could not connect: ' . mysqli_connect_error());

}


// Use prepared statements to avoid SQL injection

$sql = "SELECT * FROM tbl_login WHERE lg_username = '$username' AND lg_password = '$password' AND lg_status = '1'";

echo $sql;


$result = mysqli_query($con, $sql);



$flag = 0;

$type = '';


    while ($row = mysqli_fetch_assoc($result)) {

    $flag = 1;

    $type = $row['lg_type'];


    session_start();

    $_SESSION['user'] = $type; // store session data

    $_SESSION['username'] = $username;

}


echo $flag;

echo $type;


if ($err > 0) {

    echo "<script>location.href='index.php?msg=Invalid Username or Password'</script>";

} else if ($flag == 1 && $type == "admin") {

    echo "<script>location.href='adminhome.php'</script>";

} else if ($flag == 1 && $type == "user") {

    echo "<script>location.href='userhome.php'</script>";

} else if ($flag == 1 && $type == "faculty") {

    echo "<script>location.href='facultyhome.php'</script>";

} else {

    echo "<script>location.href='index.php?msg=Invalid Username or Password'</script>";

}



// Close the connection


mysqli_close($con);

?>


Delete row using Mysqli

 Hi all,

Use this code

...............................

<?php


include('dbconnect.php');


// Use prepared statements to avoid SQL injection

$query = "delete FROM tbl_patient where id='$_GET[id]'";

mysqli_query($con, $query);

header('location:viewdoctor.php');



?>

View table using Mysqli

 Hi all


Use this code

-----------------------

<?php

include('dbconnect.php');


// Use prepared statements to avoid SQL injection

$query = 'SELECT * FROM tbl_patient';

$result = mysqli_query($con, $query); // mysqli_query replaces mysql_query


if (!$result) {

    $message = 'ERROR: ' . mysqli_error($con); // mysqli_error replaces mysql_error

    echo $message;

    return;

} else {

    echo '

    <html>

    <head>

        <style>

            table {

                width: 80%;

                border-collapse: collapse;

                margin: 50px auto;

                font-family: Arial, sans-serif;

                background-color: #f2f2f2;

            }

            th, td {

                border: 1px solid #ddd;

                padding: 12px;

                text-align: center;

            }

            th {

                background-color: #4CAF50;

                color: white;

            }

            tr:nth-child(even) {

                background-color: #f9f9f9;

            }

            tr:hover {

                background-color: #d1e0e0;

            }

            a {

                color: red;

                text-decoration: none;

            }

            a:hover {

                text-decoration: underline;

            }

        </style>

    </head>

    <body>

        <table>

            <tr>';


    // Fetch field names dynamically and create table headers

    $fields = mysqli_fetch_fields($result); // mysqli_fetch_fields replaces mysql_fetch_field

    foreach ($fields as $field) {

        echo '<th>' . ucfirst($field->name) . '</th>';

    }

    echo '<th>Delete</th></tr>';


    // Fetch table rows

    while ($row = mysqli_fetch_row($result)) { // mysqli_fetch_row replaces mysql_fetch_row

        echo '<tr>';

        $idval = $row[0]; // Assume the first column is the id

        foreach ($row as $cell) {

            echo '<td>' . htmlspecialchars($cell) . '</td>'; // Use htmlspecialchars to prevent XSS

        }

        echo '<td><a href="delpatient.php?id=' . $idval . '">Delete</a></td>';

        echo '</tr>';

    }


    echo '</table>

    </body>

    </html>';


    mysqli_free_result($result); // mysqli_free_result replaces mysql_free_result

}


mysqli_close($con); // mysqli_close replaces mysql_close

?>


Wednesday, 12 April 2023

Apriori Algorithm

 import numpy as nm

import matplotlib.pyplot as mtp  
import pandas as pd 
from apyori import apriori  
import urllib.request

url="http://localhost/web/hupaddpairs.php?item1="

dataset = pd.read_csv('item_set1.csv')  
transactions=[]  
for i in range(0, 32):
    transactions.append([str(dataset.values[i,j])  for j in range(0,5)]) 

vals=""
rules= apriori(transactions= transactions, min_support=0.003, min_confidence = 0.2, min_lift=3, min_length=2, max_length=2) 
results= list(rules)  
for item in results:
    pair = item[0]   
    items = [x for x in pair]  
    print("Rule: " + items[0] + " -> " + items[1])  
    print("Support: " + str(item[1]))  
    print("Confidence: " + str(item[2][0][2]))  
    print("Lift: " + str(item[2][0][3]))  
    print("=====================================")  
    vals=url+items[0]+"&item2="+items[1]
    print(vals)
    webUrl = urllib.request.urlopen(vals)
    vals=""

-------------------
Data
item_set1.csv

electronics.smartphone,	electronics.video.tv			
electronics.smartphone,	electronics.video.tv,appliances.kitchen.washer		
electronics.smartphone,	electronics.audio.headphone			
electronics.audio.headphone,electronics.smartphone	appliances.environment.vacuum,kids.skates	

Tuesday, 13 December 2022

PHP and MySQL

 

MySql

Mysql is a powerful RDBMS.

Top companies in the world such as Youtube, Paypal, Linkedin, Facebook, Twitter, Cisco, Uber, Verizon, Github, Walmart, Flipcart, Alibaba, Paypal etc have adopted Mysql for this reason.

PHP programming language has built-in APIs for interacting with MySQL.

MySQL is free and open-source software under the terms of the GNU General Public License, and is also available under a variety of proprietary licenses.

MySQL has stand-alone clients that allow users to interact directly with a MySQL database using SQL, but more often, MySQL is used with other programs to implement applications that need relational database capability. MySQL is a component of the LAMP web application software stack (and others), which is an acronym for Linux, Apache, MySQL, Perl/PHP/Python.

PHP General Points

 

PHP

Front End of the application is developed using PHP.

With the help of PHP static part of the project could be easily bind with Back End.

Login sessions can be easily managed with $_SESSION variables.

As this is free software the same can be downloaded and deployed easily.

It is integrated with a number of Common databases, including PostgreSQL , MySQL, , Sybase, Informix, and Microsoft SQL Server.

PHP supports a large number of important protocols such as IMAP ,POP3,  and LDAP.

PHP can handle forms, i.e. gather data from files,  save in hard drive etc.

We  add, delete, modify elements within our database using PHP.

 We can easily handle cookies variables and set cookies.

Using PHP, you can restrict users to access some pages of your website using session.

 It can encrypt data using various algorithms. Hashing can also be done.


Wednesday, 27 April 2022

Auto ID in forms

 Hi all,

This has got three parts

1. Code in the form - saveform.php

<html>

<body>

<?php

include('dbconnect.php');

$mid=getid('student','sid');

?>

<form action=savestudent.php method=post>

Id <input type=text name=id1 value='<?php echo $mid; ?>' disabled >

<input type=hidden name=id value='<?php echo $mid; ?>'  ><br>

Name <input type=text name=name><br>

<input type=submit value='save'>

</form>

</body>

</html>


2. Code in the save part -savestudent.php



<?php

$id=$_POST['id'];

echo $id;

include('dbconnect.php')

//DB insert query part

?>


3. Include file - dbconnect.php


<?php

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("anganwadi", $con);

function getid($tablename,$fieldid)

{

$query="select max($fieldid)+1 as mid from $tablename";

echo $query;

$data=mysql_query($query);

$maxid=0;

while($row=mysql_fetch_array($data))

{

$maxid=$row['mid'];

}

return $maxid;

}

?>

Thursday, 8 April 2021

Refresh a page continually and retrieve from db

 Hi all

Use settimeout function with php

Use this code on top of your program.

<script>setTimeout(hup, 3000);

function hup()

{

location.href='predictions.php';

}

</script>

Monday, 22 February 2021

Retrieve IP address from httprequest using PHP

 Hi All,

Use this line for IP address retrieval.

This can be used to verify authenticity of feedbacks.


<?php


 $ipAddress = $_SERVER['REMOTE_ADDR'];

echo $ipAddress;


?>

Monday, 7 September 2020

Python DB Connectivity and Serial Port Connection

 HI,

Use this code


-----------------------------

import mysql.connector

import time;

import serial;

from mysql.connector import Error

from mysql.connector import errorcode

ser = serial.Serial('COM3', 9600, timeout=0,parity=serial.PARITY_EVEN, rtscts=1)


try:

   connection = mysql.connector.connect(host='localhost',

                             database='hupiot',

                             user='root',

                             password='hup')

   cur = connection.cursor()

   while True:

      s=ser.read();

      print(s);

      time.sleep(1);

      sql=("INSERT INTO timerecord (userid, recordtime, userrole ) VALUES (%s,%s,%s)")

      val=("1",s,"1")

      if s=="9":

         cur.execute(sql,val)

   connection.close()

except mysql.connector.Error as error :

    connection.rollback() #rollback if any exception occured

    print("Failed inserting record into python_users table {}".format(error))


Saturday, 20 June 2020

Graph

Hi All,
See how graph can be drawn using Google tools.

----------------------------------------------
Table structures

CREATE TABLE IF NOT EXISTS `graphdata` (
  `id` int(11) NOT NULL,
  `percentage` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `graphdata`
--

INSERT INTO `graphdata` (`id`, `percentage`) VALUES
(1, 80),
(2, 60);
----------------------------------------------------------------------

<!DOCTYPE html>
<!-- Website template by freewebsitetemplates.com -->
<html>
<head>
<meta charset="UTF-8">
<title> PROJECT MANAGEMENT</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<?php
include'dbconnect.php';
$sql="delete from graphdata";
    mysql_query($sql);

$sql="select distinct(pgid) as pgids from members";
    $data=mysql_query($sql);
    while($row=mysql_fetch_array($data))
    {
         $id=$row['pgids'];
echo $id."<br>";
$qr="select percentage from members where pgid='$id'";
echo $qr;
$sum=0;
$count=0;
$data1=mysql_query($qr);
$percentage=0;
         while($row1=mysql_fetch_array($data1))
         {
          $count=$count+1;
  $percentage=$percentage+$row1['percentage'];

         }
$sum=$sum+$percentage;
         $avg=$sum/$count;
mysql_query("insert into graphdata values('$id','$avg')");





    }





?>
</body>
</html>
<!DOCTYPE html>
<html lang="en-US">
<body>

<h1>My Web Page</h1>

<div id="piechart"></div>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
  ['Id', 'Percentage']
<?php
$sql="select * from graphdata,proreg where graphdata.id=proreg.id";
    $data=mysql_query($sql);
    while($row=mysql_fetch_array($data))
    {
         $id=$row['name'];
$avg=$row['percentage'];
?>
 
  <?php
  echo ",['$id', $avg]";
}
  ?>

]);

  // Optional; add a title and set the width and height of the chart
  var options = {'title':'My Average Day', 'width':550, 'height':400};

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}
</script>

</body>
</html>

Tuesday, 21 April 2020

Auto Id and File Upload

Hi All,
Find the code for Auto Id and File Upload in PHP...



CREATE TABLE IF NOT EXISTS `studentreg` (
  `sid` int(11) NOT NULL,
  `name` text NOT NULL,
  `address` text NOT NULL,
  `email` text NOT NULL,
  `phone` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

------------------------------------------------
studentform.php
-----------------------------------------------------
<html>
<body>
<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("snit",$con);


//Code to insert into both registration and Login table
if(isset($_POST['btnsubmit']))
{
$sql="insert into studentreg values('$_POST[id1]','$_POST

[name]','$_POST[address]','$_POST[email]','$_POST

[phone]')";
echo $sql;
$sql1="insert into login values('$_POST[id1]','$_POST[password]','student','0')";
mysql_query($sql,$con);
mysql_query($sql1,$con);

$target_dir = "uploads/";
$target_file=$target_dir .$_POST['id1'].'.jpg';
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],

$target_file) or die('Error'.mysql_error());


}

?>

<?php

//Auto generate next id in the screen.

//Query to get the highest value in table

$sql="select max(sid) as mid from studentreg";
$data=mysql_query($sql);
$id=0;
while($row=mysql_fetch_array($data))
{
 $id=$row['mid'];
}

$id=$id+1;
echo $id;
?>
<form action=# method=post  enctype="multipart/form-data">
<pre>
Id      <input name=id disabled=disabled value="<?php echo

$id ; ?>" pattern="[a-zA-Z]{2,10}" title="Enter only

characters">
<input type=hidden name=id1 value="<?php echo $id ; ?>" >
Name    <input name=name required=required maxlength=18>
Address <input name=address>
Email   <input type=email name=email>
Phone   <input name=phone pattern="[0-9]{10,12}">
Password<input name=password >
Photo   <input type="file" name="fileToUpload"

id="fileToUpload">
<input type=submit name=btnsubmit value='Save'>
</pre>
</form>

Monday, 6 April 2020

Combo Box -Validation- Auto ID Generation-Delete-Uploadfile

Hi All,

This PHP program will help you to do combobox, dynamic combobox from table, form validation , auto id generation in php form, delete from form, upload image in php etc.

---------------------------------------------------------------------------------------
<html>
<body>
<form action=savestudent.php method=post>
<table>
<tr>
<td>Id</td>
<td><input name=id ></td>
</tr>

<tr>
<td>Name</td>
<td><input name=name ></td>
</tr>
<tr>
<td>Course</td>
<td>
<select name=name >
<option value=c1>MCA</option>
<option value=c2>MTech</option>
<option value=c3>BTech</option>
</select>
</td>
</tr>
<tr>
<td>Gender</td>
<td>Male <input type=radio name=gender value=male >Female <input type=radio name=gender value=female ></td>
</tr>
<tr>
<tr>
<td></td>
<td><input type=submit value='Save'></td>
</tr>
</table>
</form>
</body>
</html>

-----------------------------------------------------------------------------------------------------------------
Now Combobox values can be generated by using table and function
So create a table course with courseid and coursename

<htm>
<body>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("hup");

function showcombobox()
{
$sql="select courseid,coursename from course";
echo $sql;
$data=mysql_query($sql);
$retvalue='';
while($row=mysql_fetch_array($data))
{
 $retvalue=$retvalue."<option value='".$row['courseid']."'>".$row['coursename']."</option>";
}
echo $retvalue;

}
?>

<form action=savestudent.php method=post>
<table>
<tr>
<td>Id</td>
<td><input name=id ></td>
</tr>

<tr>
<td>Name</td>
<td><input name=name ></td>
</tr>
<tr>
<td>Course</td>
<td>
<select name=name >
<?php
showcombobox();
?>
</select>
</td>
</tr>
<tr>
<td>Gender</td>
<td>Male <input type=radio name=gender value=male >Female <input type=radio name=gender value=female ></td>
</tr>
<tr>
<tr>
<td></td>
<td><input type=submit value='Save'></td>
</tr>
</table>
</form>
</body>
</html>

Friday, 3 April 2020

Simple View in PHP

Hi All,
See the code.... ...

<?php


//include('connect.php');
//Db connection code here


$query = 'select * from student';
$result = mysql_query($query);
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
$i = 0;
echo '<html><body><table border=1 align=center><tr>';
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo '<th>' . ucfirst($meta->name) . '</th>';
$i = $i + 1;
}
echo '<th>Delete</th>';
  
$i = 0;
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
$count = count($row);
$y = 0;
$idval='1';
while ($y < $count)
{
$c_row = current($row);
if($y==0)
$idval=$c_row;
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '<td><a href=delstudent.php?id=$idval>Delete</a></td>';
    
echo '</tr>';
$i = $i + 1;
}
echo '</table></body></html>';
mysql_free_result($result);
}
mysql_close ($con);

?>

Saturday, 22 February 2020

Dynamic Combobox

Dear all

Using this code a combo box can be dynamically populated using php code.

-------------------------
<?php
if($con=mysql_connect("localhost","root",""))
{
//echo"connected";
}
else
{
//echo"not connected";
}
mysql_select_db("fjc");



//start combo box code.

function showcombobox($tablename,$valuefield,$showfield)
{

$sql="select $valuefield,$showfield from $tablename";
echo $sql;
$data=mysql_query($sql);
$retvalue='';
while($row=mysql_fetch_array($data))
{

$retvalue=$retvalue."<option value='".$row[$valuefield]."'>".$row[$showfield]."</option>";

}

return $retvalue;
}

//start combo box code.

?>
-------------------------------

Sunday, 9 February 2020

MVC in core PHP

Hi All,
This is a post dedicated for creating MVC program using core PHP

////View

<html>
<head>
<form action="controller.php" method=post>
<b>  NAME <input type="text" name="name">
ADDRESS <input type="text" name="address">
COURSE<input type="text" name="course"></b>
<input type="submit" name=btnsub value="OK">
</form>
</html>


/////Controller

<?php
include ('model.php');
 if(isset($_POST["btnsub"]))
 {
echo "entered";
 $con=mysql_connect("localhost","root","");
 mysql_select_db("mvc",$con);
 $s=new student();
 $name=$_POST['name'];
 $address=$_POST['address'];
 $course=$_POST['course'];
 $s->insert($name,$address,$course);
  //header('location: model.php');



 }
 ?>


/////Model

<?php
class student {
function __construct() {

}

function insert($name,$address,$course ) {
echo "insert worked";
$sql=("insert into student values('$name','$address','$course')");
mysql_query($sql);

}
}
?>

Monday, 27 January 2020

Showing videos which are stored in Server using PHP

Hi All,
This code can be used to view videos which are stored in server.
Table contents are shown using reusable code here.
You have to change only the sql in the below given code.
No need to type the entire code.
Just copy and run.


-----------------------------------------------------------------------------------------------------------
<center>
<?php
include('connect.php');

$query = 'select * from upload';
$result = mysql_query($query);
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
$i = 0;
echo '<html><body><table border=1 align=center><tr>';
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo '<th>' . ucfirst($meta->name) . '</th>';
$i = $i + 1;
}
echo '<th>View</th></tr>';
$i = 0;
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
$count = count($row);
$y = 0;
$idval='1';
while ($y < $count)
{
$c_row = current($row);
if($y==0)
$idval=$c_row;
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '<td><a href=videoupload1/'.$idval.'.mp4>View Video</a></td>';
echo '</tr>';
$i = $i + 1;
}
echo '</table></body></html>';
mysql_free_result($result);
}
mysql_close ($con);

?></center>

Friday, 10 January 2020

Create a Hashtag with Auto Id

Hi All,
Using this code you can save data to a table with auto generated ID in PHP.

--------------------------
Table


CREATE TABLE IF NOT EXISTS `hashtag` (
  `hid` int(11) NOT NULL,
  `tag` text NOT NULL,
  `description` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


---------------------------

<html>
<body>
<?php

mysql_connect("localhost","root","");
mysql_select_db("tcsr");

$sql1="select max(hid) as mid from hashtag ";
$data1=mysql_query($sql1);

$id=0;

while($row=mysql_fetch_array($data1))
{


   $id=$row['mid'];
}
$id=$id+1;
echo $id;

?>
<form name="frm"   method=post enctype="multipart/form-data" >
<pre>
Id           <input type="text" value="<?php echo $id; ?>" disabled=disabled name="hid" /> <input  name="hid1" type="hidden" value="<?php echo $id; ?>" />
HashTag      <input type="text" name="hashtag" />
Description  <input type="text" name="description" />

<input name="hsubmit" type="submit" value="Upload files" />
</form>



<?php
echo "entered";
if(isset($_POST['hsubmit']))
{
echo "Entered";
$hid=$_POST['hid1'];
$hashtag=$_POST['hashtag'];
$desc=$_POST['description'];

$sql="insert into hashtag values('$hid','$hashtag','$desc')";
echo $sql;
$result=mysql_query($sql);

}

?>
</body>
</html>