...

View Full Version : Can my submit form be used to edit also?



steamngn
04-03-2007, 03:46 AM
Hi again PHP gurus!
I managed to cobble together the following page that allows a user to insert a record into our school database for events. I also need to make a way for these users to edit or delete a record in case(when) they make a mistake. Is it possible to use my submit form to do this, or do I need to create an altogether separate page? Not being a PHP guru, I need HEEEEEELLLPP!!!:eek:
Thanks in advance,
Andy

<?php
ini_set('display_errors',true);
// include the database configuration and
// open connection to database
include './config.php';
include './opendb.php';

// check if the form is submitted
if(isset($_POST['btnSign']))
{
// get the input from $_POST variable
// trim all input to remove extra spaces
$gPost_dat = trim($_POST['Post_dat']);
$gRemove_dat = trim($_POST['Remove_dat']);
$gevent_dat = trim($_POST['Event_dat']);
$gTitle = trim($_POST['Title']);
$gTitle = mysql_real_escape_string($_POST['Title']);
$garticle = trim($_POST['Details']);
$garticle = mysql_real_escape_string($_POST['Details']);
$gemailadrs = trim("mailto:".$_POST['Emailadrs']);
$gemailadrs = mysql_real_escape_string("mailto:".$_POST['Emailadrs']);
$gHyperLink = trim("http://www.".$_POST['HyperLink']);
$gHyperLink = mysql_real_escape_string("http://www.".$_POST['HyperLink']);
$glinktxt = trim($_POST['TxtHyperLink']);
$glinktxt = mysql_real_escape_string($_POST['TxtHyperLink']);
$gpubloc = trim($_POST['PubLoc']);
$gphone = trim($_POST['Phone']);
$gstarttimeh = trim($_POST['StartTimeH']);
$gstarttimem = trim($_POST['StartTimeM']);
$gstarttimeap = trim($_POST['StartTimeAP']);
$gendtimeh = trim($_POST['EndTimeH']);
$gendtimem = trim($_POST['EndTimeM']);
$gendtimeap = trim($_POST['EndTimeAP']);
$descr = trim($_POST['Descr']);

// escape the message ( if it's not already escaped )
if(!get_magic_quotes_gpc())
{
$gPost_dat = addslashes($gPost_dat);
$gRemove_dat = addslashes($gRemove_dat);
$gevent_dat = addslashes($gevent_dat);
$gTitle = addslashes($gTitle);
$garticle = addslashes($garticle);
$gemailadrs = addslashes($emailadrs);
$gHyperLink = addslashes($gHyperLink);
$glinktxt = addslashes($glinktxt);
$gpubloc = addslashes($gpubloc);
$gphone = addslashes($gphone);
$gstarttimeh = addslashes($gstarttimeh);
$gstarttimem = addslashes($gstarttimem);
$gstarttimeap = addslashes($gstarttimeap);
$gendtimeh = addslashes($gendtimeh);
$gendtimem = addslashes($gendtimem);
$gendtimeap = addslashes($gendtimeap);
$descr = addslashes($descr);

}
// prepare the query string
$query = "INSERT INTO Events (Post_dat, Remove_dat, Event_dat, Title, Email, Phone, Descr, Details, HyperLink, TxtHyperLink, PubLoc, Starttime, Endtime) " .
"VALUES ('$gPost_dat','$gRemove_dat','$gevent_dat','$gTitle','$gemailadrs','$gphone','$gdescr','$garticle',' $gHyperLink','$glinktxt','$gpubloc',concat('$gstarttimeh',':','$gstarttimem', ' ', '$gstarttimeap'),concat('$gendtimeh',':','$gendtimem', ' ', '$gendtimeap'))";
// execute the query to insert the input to database
// if query fail the script will terminate
mysql_query($query) or die('Error, query failed. ' . mysql_error());
// redirect to current page so if we click the refresh button
// the form won't be resubmitted ( as that would make duplicate entries )
ob_start();
header( "Location: http://www.chungmas.com/members/submitevent.php");
ob_end_flush;
// force to quite the script. if we don't call exit the script may
// continue before the page is redirected
exit;
}
?>
and the Form that feeds it:



<form method="post" name="submitevent" >
Enter the <b>Date</b> this event occurs:
<script type="text/javascript">DateInput('Event_dat', true, 'YYYY-MM-DD')</script>

Enter the <b>First</b> date you want this Event Post to appear:
<script type="text/javascript">DateInput('Post_dat', true, 'YYYY-MM-DD')</script>

Enter the <b>Last</b> date you want this Event Post to appear:
<script type="text/javascript">DateInput('Remove_dat', true, 'YYYY-MM-DD')</script>

Enter the <b>Start</b> time of this Event:<br>
<select name="StartTimeH">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="StartTimeM">
<option value="00">00</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
<select name="StartTimeAP">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
<br>
Enter the <b>End</b> time of this Event:<br>
<select name="EndTimeH">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="EndTimeM">
<option value="00">00</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
<select name="EndTimeAP">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>

<br>
Enter your Event <b>Headline</b> Here:<br>


<textarea name="Title" style="text-align: center" cols="60" rows="3">
</textarea>
<br>
Enter the event <b>Description</b> Here:<br>

<textarea cols=60 rows=3 name="Descr"></textarea><br>


Enter the Event <b>Details</b> Here:<br>

<textarea cols=60 rows=10 name="Details"></textarea><br>


<fieldset style="padding: 2" >
<legend>This Event is for:</legend>
<p><input type="radio" value="KO" checked name="PubLoc"><font color="#000000">Kingston Events Page<p>
<p><input type="radio" name="PubLoc" value="MO">Mahopac Event Page</p>
<p><input type="radio" name="PubLoc" value="BT">Both Kingston AND Mahopac Events Pages</p>
</font>
</fieldset>
<br> Is there an Email address where someone can request more info?<br>If so, enter it here:<br>
<input name="Emailadrs" type="text" size="60" maxlength="60"><br>
<font color="#FF0000">(Just the email address; We'll add text for it later)</font><br><br>
<br> Is there a Phone Number where someone can request more info?<br>If so, enter it here:<br>
<input name="Phone" type="text" size="12" maxlength="12"><br>
<font color="#FF0000">(Enter the number in the format ###-###-####)</font><br><br>

<br> Is there a link to another page for this article?<br>If so, enter it here:<br>
<input name="HyperLink" type="text" id="HyperLink" size="60" maxlength="60"><br>
<font color="#FF0000">(Don't enter the http://www. part; just the address)<br>(I.E. just enter chungmas.com,
not http://www.chungmas.com)</font><br><br>

Enter link text to display here:<br>
<input name="TxtHyperLink" type="text" size="60"><br>

<br><br>
<input name="btnSign" type="submit" id="btnSign" value="submit" onClick="return checkForm();">

<br>

</form>

Pennimus
04-03-2007, 11:09 AM
You could potentially use the same form, but it's simpler to clone the form on a seperate page instead.

The only differences between an edit and insert page are that on the edit page you query the database first and populate the form with the existing values for each field, then when you process the data you use an UPDATE query instead of INSERT.

steamngn
04-03-2007, 02:31 PM
Hey Pennimus,
Thanks for the reply. I guess my concern is that the users of this site may not be techno-savvy; In my mind one form would be easier for them, but perhaps I am over-thinking it. That, and I wasn't even sure if it could be done! Just for the heck of it, how would a select and update be added to a page like this? Would it be a separate block of PHP, or does it get mingled together? And how would you pass the field values to each form field? (Jeesh, I ask a lot of questions!):eek:
Anyway, My thought was to add a list box to the page to display the record identity and title, and when a user selects a given record have it populate the form with the relevant data. Does this sound like a way to go, or am I off base?
Andy

Pennimus
04-03-2007, 02:58 PM
Your method will work fine - you can either have the list link to something like edit.php?id=XX, where XX corresponds to the id of the row you want to edit, or you can have it point to itself but with some additional get or post data.

Then you use $_GET or $_POST to retrieve the ID, and pull the relevant data from your database in the normal way (using SELECT)

Then in your form values you echo out the relevant part of that row.

I assume that, having got to the stage where you are thinking about adding an edit function, you already know how to perform a SELECT query and echo the contents of the database.

Eg:



<?php
$id = $_GET["id"];
$query = mysql_query("SELECT name FROM table WHERE id='$id'");
$result = mysql_fetch_array($query);
?>
<form>
<input type="name" value="<?php echo $result["name"];?>" />
</form>


Then, when processing the data you use exactly the same code to collate the information except when you get to the INSERT stage you use UPDATE instead:



$update = mysql_qeury("UPDATE tablename SET name='$name' WHERE id='$id'");



That ought to be enough to be getting on with :thumbsup:

steamngn
04-03-2007, 03:02 PM
Ok Pennimus,
I'll have at this the next day or so. I'll keep you posted as to my progress! I guess you're right; the user won't see the url difference, so they won't know the page is different other than the fact the the form is already filled out...
Bad Andy! don't overthink!:D

iLLin
04-03-2007, 03:53 PM
Damn, I had a nice post for you but it got wiped...

Anyway lets try again :)

Keep the same form and just check for the id being submitted and is valid, then insert or update upon that.



<?php

if(isset($_GET['id']) && is_valid($_GET['id'])) {
$id = $_GET['id'];
//retrieve data row information
//maybe combine the is_valid function with the retrieval info for 1 query
}

if($submit) {
if(!empty($_POST['id']) && is_valid($_POST['id'])) {
$id = $_POST['id'];
//update data row
} else {
//insert new data row
$id = //last inserted id
}
redirect based on id to their info
}
?>

<form>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
...other form stuff
</form>


:)

aedrin
04-03-2007, 03:56 PM
but it's simpler to clone the form on a seperate page instead.

But try to maintain that, and you'll get tired of it pretty fast. I used to copy forms, when I started out. But it's just not worth it.

Whenever you make a form, you should always have verification code. If the verification fails, you have to reprint all the values in the form. This is a hook to put in existing data. Use an array to print those values. If it's a new form that was submitted, set the array to _POST. If you are editing, fill the array with the data from the database.



if ($editing) {
/* fill the $data array with data from database */
} else {
$data = $_GET;
}




...
<input type="text" name="firstname" value="<?php echo isset($data['firstname']) ? $data['firstname'] : ""; ?>" />
<input type="text" name="lastname" value="<?php echo isset($data['firstname']) ? $data['lastname'] : ""; ?>" />
...


Now you can either delete the existing data right before inserting, if you are editing. Or you can choose an INSERT or UPDATE with an if.

See it as a chance to improve your work. Instead of going for the easy method, go for the simpler method.

steamngn
04-03-2007, 04:02 PM
Hi Guys!
Brain overload! Danger Will Robinson!....
Ok, I get the idea; keep the same page, set it up so that a user can select a record to edit or enter a new one. Now, I'm stuck on how to add the SELECT (for the user to pick which record to edit) into what I already have for the INSERT. My coding experience is 100% DB (MSSQL), 80% HTML, and a getting-better-all-the-time %50 PHP. I get it, but i'm not really well versed in it. A little guidance, plllllleeeeeeeeeeeeeeeeeeeeaaaaaaaaassssseee??
(I promise not grovel!):p

aedrin
04-03-2007, 04:12 PM
What you suggested earlier is useful. A dropdown for existing ones.

You first want to display a dropdown of all the existing data.

So you do your query, then echo out the OPTIONs for the SELECT element. Add in an empty element as the first row. Set the onChange event so that it submits the form (making sure you don't try to save the data when they do).



<select name="id" onchange="submit();">
<option value="0">[New]</option>
<?php
while ($row = get_row()) {
echo '<option value="' . $row['id'] . '">' . $row['title'] . '</option>';
}
?>
</select>


Then you determine whether we are editing or a new one.



if (isset($_GET['id']) && !empty($_GET['id']) && $_GET['id'] != '0') {
$editing = true;
} else {
$editing = false;
}


Now print your form. Change the name of the button if they are editing, or saving, as not to confuse the user.

Then somewhere at the top check if the form was submit through the Save/Edit button, and then update the database record.

steamngn
04-03-2007, 04:31 PM
Ok Aedrin,
I'm gonna give it a go. I THINK I have enough info to be dangerous....
Thanks for the guidance. I will see if i can get this working on my own, and if not, I'll come crawling back!:thumbsup:
Andy

steamngn
04-03-2007, 06:07 PM
Ok,
stupid question:
(please don't hit me!)
Can I just ADD the select query into the PHP block that is already in the top, or should it/must it be separate? I pulled the site to my desk here at work and am trying to get this going....
Andy
So I Asked, and here's an update:
I put the SELECT statement into my original PHP:

<?php
ini_set('display_errors',true);
// include the database configuration and
// open connection to database
include './config.php';
include './opendb.php';
$query = 'select identity, Title from Events ORDER BY identity ASC';
$result = mysql_query($query) OR die();
// check if the form is submitted
if(isset($_POST['btnSign']))
{
// get the input from $_POST variable
// trim all input to remove extra spaces
$gPost_dat = trim($_POST['Post_dat']);
$gRemove_dat = trim($_POST['Remove_dat']);
$gevent_dat = trim($_POST['Event_dat']);
$gTitle = trim($_POST['Title']);

And then put this into the top of my form:

<select name="id" onchange="submit();">
<option value="0">[New]</option>
<?php
while ($row = get_row($result)) {
echo '<option value="' . $row['identity'] . '">' . $row['Title'] . '</option>';
}
?>
</select>

What I get when I load the page is this:
Fatal error: Call to undefined function: get_row() in /hermes/web03/b343/blu.steamngn/members/submitevent.php on line 337

aedrin
04-03-2007, 07:07 PM
It doesn't really matter where you put the SELECT query for getting the existing records.

The Update/Insert statements should be at the top, as you don't want to display the form after changes have been saved (or you could display them anyway, depending on your interface preference).

steamngn
04-03-2007, 07:19 PM
Ok,
I changed the get_row to mysql_fetch_array and now the dropdown list is showing the correct data. I will try to parse it out to each field in the form and see what happens!
Andy

steamngn
04-03-2007, 07:26 PM
See it as a chance to improve your work. Instead of going for the easy method, go for the simpler method.

I'm hammering it out, Aedrin!
Still trying to get the onchange to populate the form, but I'm on it!

aedrin
04-03-2007, 08:42 PM
get_row

I purposefully use "made up" names, because 1) I don't know what database you are using and 2) it deters certain people from copy & pasting. :)

steamngn
04-03-2007, 08:54 PM
Cool!
I like to learn and do it myself; Not being a good PHP guy (yet!) it looked to me like that was a valid function. I have to admit that I am stuck; I was able to add the query and get the dropdown list in ok, but I can't seem to get the query for the isset:

if(isset($_GET['id']) && is_valid($_GET['id'])) {
$id = $_GET['id'];
//retrieve data row information
while ($row = mysql_fetch_array($result)) {
$T = stripslashes($row[Title]);
$D = stripslashes(str_replace('\r\n', "",$row[Descr]));
$E = $row[Eventdt];
$Dt = stripslashes(str_replace('\r\n', "",$row[Details]));
$Hyp = stripslashes($row['HyperLink']);
$Txt = stripslashes(str_replace('\r\n', "",$row[TxtHyperLink]));
$Em = stripslashes($row[Email]);
$Ph = stripslashes($row[Phone]);
$St = $row[Starttime];
$End = $row[Endtime];


}
// check if the form is submitted
if(isset($_POST['btnSign']))
{
// get the input from $_POST variable
// trim all input to remove extra spaces
$gPost_dat = trim($_POST['Post_dat']);
$gRemove_dat = trim($_POST['Remove_dat']);

If I remove the _GET portion then the page will load, but as it stands it will not load at all. I will get it! (MAybe with just a little help!)
Andy

aedrin
04-03-2007, 11:11 PM
Indenting will show you the error of your ways.



if(isset($_GET['id']) && is_valid($_GET['id'])) {
$id = $_GET['id'];
//retrieve data row information
while ($row = mysql_fetch_array($result)) {
$T = stripslashes($row[Title]);
$D = stripslashes(str_replace('\r\n', "",$row[Descr]));
$E = $row[Eventdt];
$Dt = stripslashes(str_replace('\r\n', "",$row[Details]));
$Hyp = stripslashes($row['HyperLink']);
$Txt = stripslashes(str_replace('\r\n', "",$row[TxtHyperLink]));
$Em = stripslashes($row[email]);
$Ph = stripslashes($row[Phone]);
$St = $row[Starttime];
$End = $row[Endtime];
}


Notice something strange?

steamngn
04-04-2007, 02:38 PM
HEY!!! HEEEEEEEEEEYYYY!!!!
I got it!! I got it BEFORE I read your post!! Ooooohhh, i'm all tingly!!:D
I actually got this part fixed last night on my own; I will try the INSERT/UPDATE/DELETE stuff this morning, and let you know. I will also try to get a file upload portion added to this, but I'm really in the dark on that. I do have one question, though:
When I finally get this done, would you be kind enough to look over my work? I'm sure it will have need of "beautification"....
I'll keep taking the challenge of getting it done if you keep pushing me on!:thumbsup:
Have a great morning,
Andy
(PS: Yeah,yeah... proper formatting is something I always preach in the SQL world. You'd think I'd follow my own advice...)

iLLin
04-04-2007, 03:59 PM
Use more descriptive variables.

$T = stripslashes($row[Title]);
<->
$title = stripslashes($row[Title]);

..etc.

steamngn
04-04-2007, 04:05 PM
Hey iLLin,
Yeah, I already changed those. I got so excited about getting it to work that I just pounded in some stuff (Sloppy,Sloppy!!):D
I'm stuck on getting my radio buttons to switch after $_GET; that, and I need to pass some dates to a java date picker on this page, and that REALLY is screwing me up....
Moving closer to the Abyss!
Andy

aedrin
04-04-2007, 04:28 PM
I got it!! I got it BEFORE I read your post!! Ooooohhh, i'm all tingly!!

Born to code ;)

steamngn
04-05-2007, 12:32 AM
Well...... Almost!
Ok, I can't seem to get my head around this one:
How do I get my dropdown to show the record that has been selected?

<select name="id" onchange="submit();">
<option value="0">[New]</option>
<?php
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['identity'] . '">' . $row['Title'] . '</option>';
}
?>
</select>

Right now when the page loads it shows [NEW] (Good), but when I select a record from this list it still shows [NEW] (bad!)
I know I need to echo a "select" into this, but I'm stumped. $id2 is the variable that holds the record identity, so I can use that for the identity to pull. I assume I need to echo the entire listbox code, buuuuuut....
Andy

iLLin
04-05-2007, 12:51 AM
<select name="id" onchange="submit();">
<option value="0">[New]</option>
<?php
while ($row = mysql_fetch_array($result)) {
$selected = ($selected_value == $row['identity']) ? 'selected="selected"' : '';
echo '<option value="' . $row['identity'] . '" '.$selected.'>' . $row['Title'] . '</option>';
}
?>
</select>


Check to see if the record value equals the option, then mark it selected.

steamngn
04-05-2007, 02:09 AM
Ah iLLin....
This was too easy:

<select name="id" onchange="submit();">
<option value="0">[New]</option>
<?php
while ($row = mysql_fetch_array($result)) {
$selected = ($id2== $row['identity']) ? 'selected="selected"' : '';
echo '<option value="' . $row['identity'] . '" '.$selected.'>' . $row['Title'] . '</option>';
}
?>
</select>
I figured that one out quick! (Changed $selected_value to $id2)....:thumbsup:
I should probably bite my lip, I'm not done yet!
Andy

iLLin
04-05-2007, 05:28 AM
Awsome :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum