Connecting PHP to the MYSQL practicals

Connecting PHP to the MYSQL :

Important concept:-

The object operator, (->),

 It’s technically called the “object operator” . it is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj

$obj = new MyObject();

// Set a property in the $obj object called thisProperty

$obj->thisProperty = 'Fred';

// Call a method of the $obj object named getProperty

$obj->getProperty();

 Double arrow operator, (=>)

The double arrow operator, (=>), is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string-based) or numeric. 

$myArray = array(

    0 => 'Big',

    1 => 'Small',

    2 => 'Up',

    3 => 'Down'

 ===================================================

 Create connection in between php and MySQL

<?php

$servername = "localhost";

$username = "root";

$password = "";

 // Create connection

$conn = new mysqli($servername, $username, $password);

 // Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}

echo "Connected successfully";

?>

 Save this file as datacon1.php

=======================================

Select database in MySQL from PHP

<?php

$servername = "localhost";

$username = "root";

$password = "";

 // Create connection

$conn = new mysqli($servername, $username, $password);

 // Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}

echo "Connected successfully";

 /* select database  */

$mysqli->select_db("world");

 /*  we can also use following commands for select database such as :-

mysql_select_db(world”);

*/// world is the database name.

/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);

 ?>

 Save this file as datacon.php

===================================================

 Create database

We can add MySQL connection php file with this code no require details of create connection.

include_once("datacon.php");

 <?php

include_once("datacon.php");

 // Create database

$sql = "CREATE DATABASE pan2";

if ($conn->query($sql) === TRUE) {

  echo "Database created successfully";

} else {

  echo "Error creating database: " . $conn->error;

}

 $conn->close();

?><!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Untitled Document</title>

</head>

 <body>

</body>

</html>

===================================================

Create table

<?php

include_once("datacon.php");

 // sql to create table

$sql = "CREATE TABLE stu1 (sid INT(6),sname VARCHAR(30),

class VARCHAR(10))";

 if ($conn->query($sql) === TRUE) {

  echo "Table stu1 created successfully";

} else {

  echo "Error creating table: " . $conn->error;

}

 $conn->close();

?>

===================================================

Insert record into table

<?php

include_once("datacon.php");

 $sql = "INSERT INTO stu1 (sid, sname, class)

VALUES (101, 'ram', 'voc-III')";

 if ($conn->query($sql) === TRUE) {

  echo "New record created successfully";

} else {

  echo "Error: " . $sql . "<br>" . $conn->error;

}

 $conn->close();

?>

 ===================================================

Insert multiple records

<?php

include_once("datacon.php");

 $sql = "INSERT INTO stu1 (sid, sname, class) VALUES

 (102, 'ram1', 'voc-III');";

$sql .= "INSERT INTO stu1 (sid, sname, class)

VALUES (103, 'ram2', 'BCA-III');";

$sql .= "INSERT INTO stu1 (sid, sname, class)

VALUES (105, 'ram4', 'BCA-III')";

 if ($conn->multi_query($sql) === TRUE) {

  echo "New record created successfully";

} else {

  echo "Error: " . $sql . "<br>" . $conn->error;

}

 $conn->close();

?>

===================================================

Update record

<?php

include_once("datacon.php");

 $sql = "UPDATE stu1 SET sname='snyam' WHERE sid=102";

 if ($conn->query($sql) === TRUE) {

  echo "Record updated successfully";

} else {

  echo "Error updating record: " . $conn->error;

}

 $conn->close();

?>

===================================================

Delete Data From a MySQL Table in php

<?php

include_once("datacon.php");

 // sql to delete a record

$sql = "DELETE FROM stu1 WHERE sid=103";

 if ($conn->query($sql) === TRUE) {

  echo "Record deleted successfully";

} else {

  echo "Error deleting record: " . $conn->error;

}

 $conn->close();

?>


==========================

Select Data With MySQLi


<?php

include_once("datacon.php");

 

$sql = "SELECT sid, sname, class FROM stu1 ";

$result = $conn->query($sql);

 

if (mysqli_num_rows($result) > 0) {

  // output data of each row

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

    echo "studentid: " . $row["sid"]. " - student Name: " . $row["sname"]. " - class: " . $row["class"]. "<br>";

  }

} else {

  echo "0 results";

}

$conn->close();

?>

 

With where clause

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "pan2";

 

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}

 

$sql = "SELECT sid, sname, class FROM stu1 where class = 'voc-III'";

$result = $conn->query($sql);

 

if (mysqli_num_rows($result) > 0) {

  // output data of each row

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

    echo "studentid: " . $row["sid"]. " - student Name: " . $row["sname"]. " - class: " . $row["class"]. "<br>";

  }

} else {

  echo "0 results";

}

$conn->close();

?>

==================================================  

Select data from Database in HTML form

(Displaying returned data on Web pages,)

 <?php

include_once ' datacon.php';

$result = mysqli_query($conn,"SELECT * FROM myusers");

?>

<!DOCTYPE html>

<html>

 <head>

 <title> Retrive data</title>

 </head>

<body>

<?php

if (mysqli_num_rows($result) > 0) {

?>

  <table>

 

  <tr>

    <td>First Name</td>

    <td>Last Name</td>

    <td>City</td>

    <td>Email id</td>

  </tr>

<?php

$i=0;

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

?>

<tr>

    <td><?php echo $row["first_name"]; ?></td>

    <td><?php echo $row["last_name"]; ?></td>

    <td><?php echo $row["city_name"]; ?></td>

    <td><?php echo $row["email"]; ?></td>

</tr>

<?php

$i++;

}

?>

</table>

 <?php

}

else{

    echo "No result found";

}

?>

 </body>

</html>

===================================================

 Inserting data from HTML

 

<!DOCTYPE html>

<html lang="en">

  

<head>

    <title>GFG- Store Data</title>

</head>

  

<body>

    <center>

        <h1>Storing Form data in Database</h1>

  

        <form action="insert.php" method="post">

              

            <p>

                <label for="firstName">First Name:</label>

                <input type="text" name="first_name" id="firstName">

            </p>

          

            <p>

                <label for="lastName">Last Name:</label>

                <input type="text" name="last_name" id="lastName">

            </p>

               

            <p>

                <label for="Gender">Gender:</label>

                <input type="text" name="gender" id="Gender">

            </p>

             <p>

                <label for="Address">Address:</label>

                <input type="text" name="address" id="Address">

            </p>

            <p>

                <label for="emailAddress">Email Address:</label>

                <input type="text" name="email" id="emailAddress">

            </p>

             <input type="submit" value="Submit">

        </form>

    </center>

</body>

  </html>

 

Filename: insert.php

 

<!DOCTYPE html>

<html>

  <head>

    <title>Insert Page page</title>

</head>

  

<body>

    <center>

        <?php

          // servername => localhost

        // username => root

        // password => empty

        // database name => staff

        $conn = mysqli_connect("localhost", "root", "", "staff");

      

        // Check connection

        if($conn === false){

            die("ERROR: Could not connect. " 

                . mysqli_connect_error());

        }

          

        // Taking all 5 values from the form data(input)

        $first_name =  $_REQUEST['first_name'];

        $last_name = $_REQUEST['last_name'];

        $gender =  $_REQUEST['gender'];

        $address = $_REQUEST['address'];

        $email = $_REQUEST['email'];

          

        // Performing insert query execution

        // here our table name is college

        $sql = "INSERT INTO college  VALUES ('$first_name', 

            '$last_name','$gender','$address','$email')";

                  if(mysqli_query($conn, $sql)){

            echo "<h3>data stored in a database successfully." 

                . " Please browse your localhost php my admin" 

                . " to view the updated data</h3>"; 

  

            echo nl2br("\n$first_name\n $last_name\n "

                . "$gender\n $address\n $email");

        } else{

            echo "ERROR: Hush! Sorry $sql. " 

                . mysqli_error($conn);

        }

          

        // Close connection

        mysqli_close($conn);

        ?>

    </center>

</body>

  </html>

Output:-




================================================== 


Post a Comment

0 Comments