1

I've a form where i have 4 buttons which are used for "insert, update, delete and retrieve" operations for a table. I can fill in the fields and click any button and respective operations take place. The DB operations takes place in PHP. But when the data is being displayed, it goes to a separate page. I want the table data to be displayed in the same page. I know it's possible using javascript or something but I'm pretty new to this coding. So im getting very confused. Have been trying for the past 3 days. Nothing worked out. If anyone could teach me clearly.

HTML:

<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="open.php">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html> 

PHP:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error()) 
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];


if(isset($_POST['insert'])){
        $insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
        if($conn->query($insert) === TRUE) {
        echo ("Input data entered successfully");
        } else {
        echo ("Input data failed to be entered" . $conn->error());
        }
        $conn->close();
} elseif(isset($_POST['update'])) {

        $update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
        mysql_query($update);
        if($conn->query($update) === TRUE) {
        echo ("Data updated successfully");
        } else {
        echo ("Data cant be updated" . $conn->error());
        }
        $conn->close();
} elseif(isset($_POST['delete'])) {
        $id = $_POST['Id'];
        $delete = "delete from ins where Id='".$id."'";
        if($conn->query($delete) === TRUE) {
        echo ("Data deleted successfully");
        } else {
        echo ("Data cant be updated" . $conn->error());
        }
        $conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
  }
 mysqli_free_result($result);
}}
$conn->close();
?>
Naga Naveen
  • 99
  • 1
  • 4
  • 16
  • remove action attribute. Action attribute redirects you on open.php page. Write all php code written in open.php on same file with appropriate condition. – Manish Shukla Apr 17 '15 at 06:35

5 Answers5

1

The easiest way to do this is that you should use ajax for this. On clicking each of the buttons send the action to separate files or methods. Retrieve whatever comes depending on the type of which action was submitted and successfully update the page. For eg: If you are retrieving then on click of retrieve you send it to some page where you retrieve the details and return it to the page and just update it. It's pretty easy if you do some google on this. Make sure all your button actions go to proper respective page. Hope this was helpful.

As you mentioned this is one example here: for retrieving(I expect you know how to call another file using ajax and return values.)

$.ajax({
        url: 'retrieve.php',
        type: 'post',
        data: { id: id, name: name, blood_group: blood_group },
        success: function(your_success_variable) { 

Here your_success_variable can be an array or json whatever you wish to send from the other file back just don't forget to return

        $('#blood_group').value(your_success_variable['blood_group]);           
                }
            });
Preeti Maurya
  • 431
  • 1
  • 7
  • 17
  • I can understand what you're telling. I've googled it and no proper answer. The above coding is completely fine, but the data is being showed in a different page. using Ajax helps me out, but can you please elaborate? I mean like, any sample coding? If i have that, may be i can do it myself. Sure it was helpful – Naga Naveen Apr 17 '15 at 06:34
1

You can do it by using two method. First: Create two file one for display your work another for operation. when you submit your form it will go on operation page and when after opration is complete you have to set page location to working page like this. header('location:working page.php');

Second: by using Ajax.

Sourabh
  • 500
  • 2
  • 14
1

When the user clicks a SUBMIT-button, your FORM is submitted to open.php on your server. The browser is then taken to that page; displaying the output of your PHP script.

If you don't want to redirect the user, use AJAX in JavaScript as suggested above. There's a nice example at: How to make an AJAX call without jQuery?

The neatest way is to use jQuery, but it's more pedagogical to follow the plain JavaScript example. Essentially, you change your <input type="submit"> to <input type="button">, and add onClick="performAction('insert');" to each button (with the action string according to each operation). The function performAction(act) is declared in JavaScript in your HTML page, and creates an (asychronous!) AJAX call to your open.php script.

Right now you're submitting the FORM as POST-data. The AJAX call will have to pass the data as (URL-encoded!) GET-data, so performAction(act) appends the FORM data onto the call to open.php. (I presume it's possible to call AJAX with POST-data, and do all this in a more elegant way, but this will work. Hopefully a nice learning example.)

function performAction (act) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               alert('Request OK, result was: ' + xmlhttp.responseText);
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
               alert('something else other than 200 was returned')
           }
        }
    }

    var GET_encoded_params = "action=" + act 
        + "&Id=" + encodeURIComponent(document.forms[0].Id.value)
        + "&Name=" + encodeURIComponent(document.forms[0].Name.value)
        + "&BloodGroup=" + encodeURIComponent(document.forms[0].BloodGroup.value);

    xmlhttp.open("GET", "open.php?" + GET_encoded_params, true);
    xmlhttp.send();
}

Note that your PHP script might have to "get" the GET-data slightly different than you're getting the POST-data now, but that should be a minor change. You will also need to get the desired action (insert, update, delete, retrieve) from the new action parameter.

Code was borrowed from How to make an AJAX call without jQuery? and modified without actually testing. Beware of typos :) and have fun!

Community
  • 1
  • 1
joakimk
  • 822
  • 9
  • 26
0

retrieve button can be placed in a new form where action will be on the same page or empty right now you have placed in a form where action is open.php so every action is performing on that particular page.This will definitely help you if any error occurs let me know.

else if(isset($_POST['retrieve'])) {
    $id = $_POST['Id'];
    $retrieve = "SELECT * FROM `ins` WHERE `Id` = '".$id."';
    if ($result=mysqli_query($conn,$retrieve))
    {
    while ($row=mysqli_fetch_row($result))
    {?>
    <table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Blood Group</td>
    </tr>
    <tr>
    <td><?php echo $row[0];?></td>
    <td><?php echo$row[1];?></td>
    <td><?php echo$row[2];?></td>
    </tr>
    </table>
     <?php  }
     mysqli_free_result($result);
    }}?>
Vivek Singh
  • 2,453
  • 1
  • 14
  • 27
0

In your code you are directly printing the echo statement in the while loop.Just use a variable $msg which will store all the contents.So your code will be

<?php
    $msg="";
  $msg.= '<table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Blood Group</td>
    </tr>';

  while ($row=mysqli_fetch_row($result))
    {
   $msg.=' <tr>
    <td>'.$row[0].'</td>
    <td>'.$row[1].'</td>
    <td>'.$row[2].'</td>
    </tr>;'

      }
    $msg.='</table>';
   ?>

After this in your html just echo the variable $msg so your html code will be

<body>
<h1></h1>
<form>...</form>
<?php echo $msg;?>
</body>
rahul patel
  • 262
  • 1
  • 2
  • 15