Jump to content

Update Form using PHP


brownbrod
Go to solution Solved by tazmith,

Recommended Posts

I have created a form to update records using the ID primary key.    I am unable to use the Drop Down menu to select the record to update.     I believe I have everything else correct.   I would greatly appreciate your feedback.

 

Thanks,

 

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>

<body>
<?php

$connect=mysql_connect('us70tudbs001.zam.alcatel-lucent.com:3306','norab','norab') or die("Unable to Connect");
@mysql_select_db('rightfirst') or die("Could not open the db");

$query="SELECT * FROM contacts";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());

$i=0;

while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['id'];
$i++;
}
$total_elmt=count($roll);
?>
<form method="post" action="">
Select the ID No. to Update:  <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?></option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
First Name: <input name="first" type="text" /><br />
Last Name: <input name="last" type="text" /><br />
Phone: <input name="phone" type="text" /><br />
<input name="submit" type="submit" value="Updated"/><br />
<input name="reset" type="reset" value="Reset" />
</form>

<?php
if(isset($_POST['submit']))
{
$value=$_POST['sel'];
$first=$_POST['first'];
$last=$_POST['last'];
$phone=$_POST['phone'];

$query2 = "UPDATE contacts SET
first='$first',last='$last',phone='$phone' WHERE
id='$value'";
$result2=mysql_query($query2) or die("Query Failed :
".mysql_error());
echo "Successfully Updated";
}
?>
<p align=right><a href="view.php">VIEW RECORDS</a></p>

</body>

</html>

Link to comment
Share on other sites


<?php

/*

* PDO version.

*/



$host = 'host';

$dbname = 'db_name';

$user = 'db_user';

$pass = 'db_pass';



try

{  

    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

}

catch(PDOException $e)

{

    echo $e->getMessage();

}





echo '<form method="POST">Select id to edit:

    <select name="id">';

    $query = $dbh->query('SELECT id FROM contacts ORDER BY id ASC');

    foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row)

    {

              echo '<option value="'.$row['id'].'">'.$row['id'].'</option>';

    }

    

    echo '</select>';

    

    echo '<br /><div>

            First Name: <input name="first" type="text" /><br />';



       echo '<input type="submit" name="submit" id="submit" value="Submit" />

            </form>';

            

        if (isset($_POST['submit']))

        {

               echo '<br />Editing ID: '.htmlspecialchars($_POST['id'],ENT_QUOTES). '';            

 

            if (empty($_POST['first']) === false)

            {        

                 //firstname has been edited, lets update.

                $update_query = $dbh->prepare('UPDATE contacts SET ' . 'first=:first WHERE ' . 'id=:id ');

                $update_query->bindParam(':first', $_POST['first']);

                $update_query->bindParam(':id', $_POST['id'], PDO::PARAM_INT);

                $update_query->execute();    

                echo '<br />Updated firstname to '.htmlspecialchars($_POST['first'],ENT_QUOTES).'';

            }

            

        }



        /*

   

/*

* mysql_ version.

*/



echo '<form method="POST">Select id to edit:

    <select name="id" id="ids">';

    $query = "SELECT id FROM contacts ORDER BY id ASC";

    $result = mysql_query($query) or die ( mysql_error ());

    while ($row = mysql_fetch_array($result,MYSQL_ASSOC))

    {

              echo '<option value="'.$row['id'].'">'.$row['id'].'</option>';

    }

    

    echo '</select>';

    

    echo '<br /><div>

            First Name: <input name="first" type="text" /><br />';



      

      echo '<input type="submit" name="submit" id="submit" value="Submit" />

            </form>';

            

        if (isset($_POST['submit']))

        {

            echo '<br /><br />Editing id: ' .htmlspecialchars($_POST['id'],ENT_QUOTES). '';

            

            if (empty($_POST['first']) === false)

            {        

                $id = (int)$_POST['id'];

                $firstname = mysql_real_escape_string($_POST['first']);

                $update_query = "UPDATE contacts SET first = '$firstname' WHERE id = '$id'");

                $update_result = mysql_query($update_result) or die ( mysql_error ());    

                echo '<br />Updated firstname to '.htmlspecialchars($_POST['first'],ENT_QUOTES).'';

            }

        }

       

?>

 

Edited by tazmith
Link to comment
Share on other sites

This worked perfectly.   Now. is there a way to show what the old value is before you udpate it?   What I have seen looks to be very complexed.    For example:   Let's say I am updating ID 5 and I want to make sure it belongs to Catherine ('first').    How would I do that?

 

Thanks so much for your help. 

Link to comment
Share on other sites

Better option would be to populate the select field with the users first name, setting the id as the value for that option, eg

echo '<form method="POST">Select name to edit: <select name="id">';

    $query = $dbh->query('SELECT id, first FROM contacts ORDER BY first ASC');

    foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row)
    {
              // set record id as value, and first name as option label
              echo '<option value="'.$row['id'].'">'.$row['first'].'</option>';
    }

    echo '</select>';

Now you'd select the the name you want to edit, and then when the form is submitted the name will be updated to whatever you entered into the name field.

Edited by Ch0cu3r
Link to comment
Share on other sites

I need to update the Name using the "ID" that is associated with the name.   So what I was wondering is can I view what is already in the "first" field before it is changed?

 

if you wanted to you could have a drop down with the ID'S, and submit leading to a page like update.php?updateid=userid which will than show the input fields for first, last, ect. And than on that submit, create the POST submit.

Link to comment
Share on other sites

  • Solution

Hope this helps you. It's basic, this can be done in many ways, but here's a re-vamped version of what I did in my 1st post.

 

Note: I wen't with the PDO version, because mysql_ is just bad practice in my opinion, but that's only my opinion :)

<?php
 
$host = 'host';
$dbname = 'db_name';
$user = 'db_user';
$pass = 'db_pass';
 
try
{  
    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
 
 
if (!isset($_POST['selectid']) && !isset($_POST['submit']))
{
 
     echo '<form method="POST">Select ID to edit:
     <select name="id">';
     $query = $dbh->query('SELECT id FROM contacts ORDER BY id ASC');
     foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row)
     {
         echo '<option value="'.$row['id'].'">'.$row['id'].'</option>';
     }
 
     echo '</select>';
 
     echo '<input type="submit" name="selectid" id="selectid" value="Submit" />
     </form>';
}
 
     //selecting the id.
     if (isset($_POST['selectid']))
     {
         $query = $dbh->prepare('SELECT first,last,id FROM contacts WHERE ' . 'id=:id ');
         $query->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
         $query->execute();
         $row = $query->fetch(PDO::FETCH_ASSOC);
         $count = $query->rowCount();
        
         //incase of POST data manipulation
         if ($count < 1)
         {
             die('Error: User does not exist!');
         }
         
         echo 'Viewing ID: '.$row['id'].' Firstname: '.$row['first'].'';
         
         //the form.
         echo '<br /><br />
         <form method="POST"><div>
         First Name: <input type="text" name="first" value="'.$row['first'].'" /><br />
         Last Name: <input type="text" name="last" value="'.$row['last'].'" /><br />
         <input type="hidden" name="id" value="'.$row['id'].'" />
         <input type="submit" name="submit" id="submit" value="Submit" />';
                  
         echo '<br /><br /><a href="pagehere.php">go back</a>';
     }
     
     //submitting.
     if (isset($_POST['submit']))
     {
        if (empty($_POST['first']) === false)
        {
            //update firstname, since it was updated.
            $firstname_update = $dbh->prepare('UPDATE contacts SET ' . 'first=:first WHERE ' . 'id=:id ');
            $firstname_update->bindParam(':firstname', $_POST['first']);
            $firstname_update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
            $firstname_update->execute();
     
           //echo if wanted.
           echo 'Updating Firstname of ID: '.htmlspecialchars($_POST['id'],ENT_QUOTES).' to '.htmlspecialchars($_POST['first'],ENT_QUOTES).'';
     
          //just continue onward for lastname, phone, whatever you wan't really.
     
          echo '<br /><br /><a href="pagehere.php">go back</a>';
        }
     }
?>
Link to comment
Share on other sites

One more question.   Using this formula can I update two fields in one submit?   For example: 

 

//update firstname, since it was updated.
            $firstname_update = $dbh->prepare('UPDATE contacts SET ' . 'first=:first WHERE ' . 'id=:id ');
            $firstname_update->bindParam(':firstname', $_POST['first']);
            $firstname_update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
            $firstname_update->execute();

 

//update lastname, since it was updated.
            $lastname_update = $dbh->prepare('UPDATE contacts SET ' . last=:lastWHERE ' . 'id=:id ');
            $lastname_update->bindParam(':lastname, $_POST[last]);
            $lastname_update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
            $lastname_update->execute();

 

So when I click "SUBMIT" it updates both?

 

This is just an example.

 

I greatly appreciate your feedback.   Thanks so much!!!

 

Link to comment
Share on other sites

One more question.   Using this formula can I update two fields in one submit?   For example: 

 

//update firstname, since it was updated.

            $firstname_update = $dbh->prepare('UPDATE contacts SET ' . 'first=:first WHERE ' . 'id=:id ');

            $firstname_update->bindParam(':firstname', $_POST['first']);

            $firstname_update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);

            $firstname_update->execute();

 

//update lastname, since it was updated.

            $lastname_update = $dbh->prepare('UPDATE contacts SET ' . last=:lastWHERE ' . 'id=:id ');

            $lastname_update->bindParam(':lastname, $_POST[last]);

            $lastname_update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);

            $lastname_update->execute();

 

So when I click "SUBMIT" it updates both?

 

This is just an example.

 

I greatly appreciate your feedback.   Thanks so much!!!

Yes, you can update the lastname in a separate query. But it is more effeicent to update the firstname, and lastname within one query, using

//update firstname and lastname fields
$update = $dbh->prepare('UPDATE contacts SET first=:firstname, last=:lastname WHERE id=:id '); /* the update query */
$update->bindParam(':firstname', $_POST['first']); /* the firstname field */
$update->bindParam(':lastname', $_POST['last']);   /* the lastname field */
$update->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$update->execute();
Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.