Drop down box to populate fields for modification


#1

Hi

This is my first post on here so hello, and before we go any further I have next to no real knowledge of PHP.

I am in the process of building a website located at : http://www.ilt.bridgwater.ac.uk/~staua

The site is primarily written in html, but I have a couple of mysql table linked to it via php.

Everything is working fine except for one thing?.on the contacts link on the left hand side I want to be able to do the following:

Click on the link ---->open up my table (mysql) called ?contactslists.php?

This opens in the frame called main. This currently works fine?

Problem starts here.

I want to be able to amend a record, ideally I would like to be able to click on my amend records button and then give me a drop down box to select the record to amend.

I then want the select record to populate the fields on the form that is currently visible after the amend records button is selected.

I would then need a button to confirm and update my table.

Below is the code for my phpfiles

Upon clicking the contacts on the left frame the following file is activated:

<html>
<head>
<title>RTFC Contacts</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<?php
     import_request_variables('p');
     if (isset($name) && isset($email) && isset($position) && isset($tel))
    {
        // check user input here
        $dberror = "";
        $ret = add_to_database($name,$position,$email,$tel,$dberror);
        if (!$ret)
            print "Error: $dberror<br />";
       else
            print "<h2>Thank you very much, $name has been added </h2>";
    }
    else
        write_form();
function add_to_database($name, $position, $email, $tel, &$dberror)
{
    $user = "username";
    $pass = "password";
    $db = "database";
    $link = mysql_connect("localhost",$user,$pass);
    if (!$link)
    {
        $dberror = "Couldn't connect to MySQL server";
        return false;
    }
    if (!mysql_select_db($db, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    $query="INSERT INTO Contacts (Name, Position, Email, Tel)
   	VALUES('$name', '$position', '$email', '$tel' )";
    if (!mysql_query($query, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    return true;
//  mysql_close($link);
}
function write_form()
{
    global $PHP_SELF;
    print "<form action="$PHP_SELF"method="POST">n";
    print "<p><h2>Please Ammend Details As Required</h2></p>";
    print "<form action="$PHP_SELF" method="POST">n";
    print " <p> Officials Name</p>n";
    print "<input type="text" name="name">"; 
	print " <p> Officials Position</p>n";
    print "<input type="text" name="position">"; 
	print " <p> Your e-mail address</p>n";
    print "<input type="text" name="email">";
	print " <p> Officials Tel</p>n";
    print "<input type="text" name="tel">"; 
    print "<p><input type="submit" value="Register"></p>n</form>n";
    print "";
?>
</td><td>
<?php
}
?>
</body>
</html>

When the Amend button is clicked on the above form the following phpfile is activated:

[code]

Contacts List <?php $user = "username"; $pass = "password"; $db = "database"; $link = mysql_connect("localhost",$user,$pass); if (!$link) die("Couldn't connect to MySQL server"); mysql_select_db($db, $link) or die("Couldn't open $db: ".mysql_error()); $result = mysql_query("SELECT * FROM Contacts"); $num_rows = mysql_num_rows($result); print "

RTFC Officials Contact Details

"; print "n"; while ($a_row = mysql_fetch_row($result)) { print "n"; foreach ($a_row as $field) print "tn"; print "n"; } print "
$field
n"; print "n"; print "n"; print "n"; mysql_close($link); ?> [/code]

I hope this makes some sense, please help

Andy


#2

go to http://www.codewalkers.com and go to the tutorials/basics section. In there is a tutorial called “Creating Dynamic Websites with MySQL and PHP”. You can skip through most of it and just go to the section where they are “Editing Data”. It should show you how to do just about everything you are asking. You might wish to check out the whole tutorial to get a stronger grasp of PHP fundamentals. The tutorial covers everything from installation to querying and display of data.


#3

right many thanks, but i have had a slight change of angle here, which i know makes it difficult for you to hit a moving target, but still…

i have now opted for radio buttons

i have the following code which sort of works to a point:

it is founsd at: http://www.ilt.bridgwater.ac.uk/~staua/contactslist.php


contacts list:

html>
<head>
<title>Contacts List</title>
<link rel="stylesheet" href="stylesheet.css" />
</head>
<body>
<?php    
    $user = "username";
    $pass = "password";  
    $db = "dbname"; 
   $link = mysql_connect("localhost",$user,$pass);
    if (!$link)        die("Couldn't connect to MySQL server");
    mysql_select_db($db, $link)        or die("Couldn't open $db: ".mysql_error());
    $result = mysql_query("SELECT * FROM Contacts");
    $num_rows = mysql_num_rows($result);
    print "<h2>RTFC Officials Contact Details</h2>";
    print "<form method='post' action='Contacts.php'>n";
    print "<table border="1">n";
    while ($a_row = mysql_fetch_row($result))        
    {
        print "<tr>n";
    if ($a_row[1] == "")
          print "t<td>&nbsp;</td>n";
      else                    
          print "t<td>$a_row[1]</td>n";
    if ($a_row[2] == "")
          print "t<td>&nbsp;</td>n";
      else                    
          print "t<td>$a_row[2]</td>n";
    if ($a_row[3] == "")
          print "t<td>&nbsp;</td>n";
      else                    
          print "t<td>$a_row[3]</td>n";
    if ($a_row[4] == "")
          print "t<td>&nbsp;</td>n";
      else                    
          print "t<td>$a_row[4]</td>n";
    print "t<td>$field</td><td><input name='opt' type='radio' value=$a_row[0]></td>n";
        print "</tr>n";
            }    
    print "</table>n";
    print "<p><input type="submit" value="Add A New Record"></p>n";
    print "</form>n";    mysql_close($link);?>
</body>
</html>

how this works is that if no radio button is clicked it should act as a new entry is to be added, however if a radio button is used then it will take on the Amend process to alter current data.

when the radio button is activated and the button clicked the following code is used:


Contacts.php


<html>
<head>
<title>RTFC Newsletter</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<?php
    import_request_variables('p');
    if (isset($opt))
    {
        if (isset($name2) && isset($email2) && isset($position2) && isset($tel2))
        {
            // check user input here
            $dberror = "";
            $ret = update_database($name2,$position2,$email2,$tel2,$dberror);
            if (!$ret)
                print "Error: $dberror<br />";
            else
                print "<h2>Thank you very much, $name has been added </h2>";
        }
        else
        {
            $user = "username";
            $pass = "password";  
            $db = "dbname"; 
            $link = mysql_connect("localhost",$user,$pass);
            if (!$link)        die("Couldn't connect to MySQL server");
            mysql_select_db($db, $link)        or die("Couldn't open $db: ".mysql_error());
            $result = mysql_query("SELECT * FROM Contacts WHERE ID='".$pos."'");
            $num_rows = mysql_num_rows($result);
            $a_row = mysql_fetch_row($result);
    print "numrows = '$num_rows'";
            write_form2($a_row[1], $a_row[2], $a_row[3], $a_row[4]);
        }
    }
    else
    {
        if (isset($name) && isset($email) && isset($position) && isset($tel))
        {
            // check user input here
            $dberror = "";
            $ret = add_to_database($name,$position,$email,$tel,$dberror);
            if (!$ret)
                print "Error: $dberror<br />";
            else
                print "<h2>Thank you very much, $name has been added </h2>";
        }
        else
            write_form();
    }


function add_to_database($name, $position, $email, $tel, &$dberror)
{
    $user = "username";
    $pass = "password";
    $db = "dbname";
    $link = mysql_connect("localhost",$user,$pass);
    if (!$link)
    {
        $dberror = "Couldn't connect to MySQL server";
        return false;
    }
    if (!mysql_select_db($db, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    $query="INSERT INTO Contacts (Name, Position, Email, Tel)
       VALUES('$name', '$position', '$email', '$tel' )";
    if (!mysql_query($query, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    return true;
//  mysql_close($link);
}

function update_database($name2, $position2, $email2, $tel2, &$dberror)
{
    $user = "username";
    $pass = "password";
    $db = "dbname";
    $link = mysql_connect("localhost",$user,$pass);
    if (!$link)
    {
        $dberror = "Couldn't connect to MySQL server";
        return false;
    }
    if (!mysql_select_db($db, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    $query="UPDATE Contacts SET Name='$name2', Position='$position2', Email='$email2', Tel='$tel2'
       WHERE ID='$pos'";
    if (!mysql_query($query, $link))
    {
        $dberror = mysql_error();
        return false;
    }
    return true;
//  mysql_close($link);
}

function write_form()
{
    global $PHP_SELF;
    print "<form action="$PHP_SELF"method="POST">n";
    print "<p><h2>Please Add Details As Required</h2></p>";
    print "<form action="$PHP_SELF" method="POST">n";
    print " <p> Officials Name</p>n";
    print "<input type="text" name="name">"; 
    print " <p> Officials Position</p>n";
    print "<input type="text" name="position">"; 
    print " <p> Your e-mail address</p>n";
    print "<input type="text" name="email">";
    print " <p> Officials Tel</p>n";
    print "<input type="text" name="tel">"; 
    print "<p><input type="submit" value="Register"></p>n</form>n";
    print "";
}

function write_form2($name2, $position2, $email2, $tel2)
{
    global $PHP_SELF;
    print "name2 = '$name2'";
    print "<form action="$PHP_SELF"method="POST">n";
    print "<p><h2>Please Ammend Details As Required</h2></p>";
    print "<form action="$PHP_SELF" method="POST">n";
    print " <p> Officials Name</p>n";
    print "<input type="text" name="name2" value=$name2>"; 
    print " <p> Officials Position</p>n";
    print "<input type="text" name="position2" value=$position2>"; 
    print " <p> Your e-mail address</p>n";
    print "<input type="text" name="email2" value=$email2>";
    print " <p> Officials Tel</p>n";
    print "<input type="text" name="tel2" value=$tel2>";
    print "<input type="hidden" name="pos" value=$pos>";
    print "<p><input type="submit" value="Register"></p>n</form>n";
    print "";
}
?>
<? print "opt = '$opt'"; ?>
</body>
</html>

the trouble i am having is that i want the data that is attached to the relevant radio button to be copied across to the fields for ammending, but they are not being transferred.

i am really desperate for some help here please, i am even prepared to give you access to my site if that help.


#4

let’s make sure I understand what you are doing… if the radio button is clicked it sets a flag to “Amend”, and you can’t figure out how to get the old data loaded into the new form? Now if my summation is correct then you need to query the database and extract the data needed to load the form fields if the flag says “Amend”.

psuedocode:

/* handles update query */
if (alterations submit)
{
    validate data
    run update query
    tell user update completed or not as necessary
}
/* handles insert query */
elseif (radio button unset)
{
    validate data
    run insert query
    tell user insert completed or not as necessary
}
/* pulls data to be updated into form */
else
{
    query database to get form fields data
    display form
        display the data retrieved in the fields of form
        display submit alterations button
}

Now this is just the basic logic involved (Assumes first form submitted) and yes there are better ways of doing it (Ex: switch). Again you will have to go to the first tutorial I first suggested as well as “Working with Forms and PHP” to find out how to impliment this logic but it isn’t so hard. As you go along and need help let us know.


#5

your ammuption is correct, if the button is highlighted i want to ammend if it isnt selected it would act as an Add new member.

with regards to the code you have posted thank you very much, but is there any way you could highlight wher or how i would fit this into my pge please.

I am sorry if i am appearing dumb here but have very little knowledge with this php.

cheers

Andy


#6

OK I assume you didn’t write the code your showing so you have no knowledge of how it is working. If this is a third party script I suggest you go to the place/person/site you got it from and talk to them because they will be better able to help you and will be able to quickly solve your problem. If this is your first programming experiment - your about to get dirty. Learning how to think like a coder is the hardest part and it doesn’t happen overnight.

here is your code and what it is doing

// if the radio button is set
if (isset($opt))
{
        // if all the fields have data
        if (isset($name2) && isset($email2) && isset($position2) && isset($tel2))
        {
            // check user input here
            $dberror = "";
            // run your update routine aka function
            $ret = update_database($name2,$position2,$email2,$tel2,$dberror);
            // if there is an error in the return value do this 
            if (!$ret)
                print "Error: $dberror<br />";
            // otherwise do this
            else
                print "<h2>Thank you very much, $name has been added </h2>";
        }
        
        // do this if fields are missing
        else
        {
            $user = "username";
            $pass = "password"; 
            $db = "dbname";
            // connect to the database
            $link = mysql_connect("localhost",$user,$pass);
            // handle no connection error
            if (!$link)        
            {
                die("Couldn't connect to MySQL server");
            }
            // select database and if there is a problem stop program from running and display error message 
            mysql_select_db($db, $link) or die("Couldn't open $db: ".mysql_error());
            // select all info where the ID equals $pos
            $result = mysql_query("SELECT * FROM Contacts WHERE ID='".$pos."'");
            // get number of rows returned though I don't see where you use it
            $num_rows = mysql_num_rows($result);
            // get the actual returned data
            $a_row = mysql_fetch_row($result);           
            print "numrows = '$num_rows'";
            // run your write_form2 routine (function)
            write_form2($a_row[1], $a_row[2], $a_row[3], $a_row[4]);
        }
}
// if radio button not set
else
{
        // if all the fields have data
        if (isset($name) && isset($email) && isset($position) && isset($tel))
        {
            // check user input here
            $dberror = "";
            // run your insert routine aka function
            $ret = add_to_database($name,$position,$email,$tel,$dberror);
            // if there is an error in the return value do this 
            if (!$ret)
            {
                print "Error: $dberror<br />";
            }
            // otherwise do this
            else
            {
                print "<h2>Thank you very much, $name has been added </h2>";
             }
        }
        // do this if fields are missing
        else
        {
            write_form();
        }
    }  

As you can see your code does most of what i suggested (in a slightly different order maybe even a better order) and anything it is missing you should be able to add or move. If you are still having problems it will be time to debug… add echo statements in your code to display variables and branches in logic (if statements, function calls). This will show you how the logic in your program is flowing as well as the variables involved. If the program doesn’t flow as you thought - why not? where does it go different then you thought it would? Are the variables as you would expect? We will have to know EXACTLY where the problems are to help you fix them.

You have all (or at least most) of the parts to make it work. We just have to get them working properly and in the right order. Not hard but it can take a while to wrap your brain around. :) I like to think of a program as a puzzle that is waiting for me to solve it. And I hate letting an inanimate object kick my butt (though it has happened more then a few times).

FYI - coding style tends to be a very personal thing but I would suggest you start using brackets for single line if/else statements. It will help you think/ group your statements even if it isn’t necessary (also just good form).