Thread: PHP form Creates Blank DB entries

PHP form Creates Blank DB entries

From
Michael Hanna
Date:
I can post with this code, however the result is a new row in the
table, where each column is blank except for the serial number. Any
ideas? PG 7.3.3, PHP 4.3.0

it can be tested at :

http://www.siddha.ca/healthnotes/add.php

view the addressbook table at:

http://www.siddha.ca/healthnotes/index.php

Michael

-----

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>

</body>
</html>
<html>
<head><basefont face="Arial"></head>
<body>
<h2>Address Book</h2>

<?
// form not yet submitted
// display form
if ($_POST['submit'] != "Add")
{
?>

        <form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST">
         Name:<br>
         <input name="name" type="text" size="50">
         <p>
         Address:<br>
         <textarea name="address" rows="6" cols="40"></textarea>
         <p>
         Tel:<br>
         <input name="tel" type="text" size="10">
         <p>
         Email:<br>
         <input name="email" type="text" size="30">
         <p>
         <input type="submit" name="submit" value="Add">
         </form>
<?
}
else
{
         // form submitted
         // prepare to insert data

         // database access parameters
         // alter this as per your configuration
         $host = "localhost";
         $user = "<MYUSER>";
         $pass = "<MYPASS>";
         $db = "test";

         // open a connection to the database server
         $connection = pg_connect("host=$host dbname=$db user=$user
password=$pass");

         if (!$connection)
         {
                 die("Could not open connection to database server");
         }

         // error checks on form submission go here

         // generate and execute a query
         $query = "INSERT INTO addressbook VALUES
(nextval('addressbook_id_seq'), '$name', '$address', '$tel', '$email')";
         $result = pg_query($connection, $query) or die("Error in query:
$query. " . pg_last_error($connection));

         echo "Data successfully added.";

         // close database connection
         pg_close($connection);
}
?>
</body>
</html>

Re: PHP form Creates Blank DB entries

From
Frank Bax
Date:
At 12:16 PM 6/30/03, Michael Hanna wrote:
>// error checks on form submission go here
>// generate and execute a query
>$query = "INSERT INTO addressbook VALUES (nextval('addressbook_id_seq'),
>'$name', '$address', '$tel', '$email')";
>$result = pg_query($connection, $query)
>         or die("Error in query: $query. " . pg_last_error($connection));
>echo "Data successfully added.";
>// close database connection
>pg_close($connection); } ?>


Probably because "register globals" is off (default changed since 4.2.0).
         http://ca3.php.net/register_globals

Insert the following lines before "$query = ..." line:

$name = $_POST[name];
$address = $_POST[address];
$tel = $_POST[tel];
$email = $_POST[email];



Re: PHP form Creates Blank DB entries

From
Jeff
Date:
On Mon, Jun 30, 2003 at 01:23:17PM -0400, Frank Bax wrote:
[..snipped..]
> $name = $_POST[name];
> $address = $_POST[address];
> $tel = $_POST[tel];
> $email = $_POST[email];
[..snipped..]

this will work OK, but is considered a bad idea, and php will throw a
warning (as it should) that you are accessing a key in an associative array
without properly quoting things.

if you want to do it "properly", try this instead:

$name = $_POST["name"];
$address = $_POST["address"];
$tel = $_POST["tel"];
$email = $_POST["email"];

the above will execute without warnings or errors.

also, I would suggest running each of the variables through a function that
strips out html tags (since you don't really care about allowing them in
this case, right?).. you can do that with strip_tags.. see
http://php.net/strip_tags

there are some other things you should do with user input too, to protect
your code and database from vulnerabilities. in eros, I implemented
something called preparestring(), which, in addition to strip_tags, makes a
call to htmlentities() and a couple other things, just to be *really*
*extra* safe about things, and avoid bugs or problems down the road when
someone does something rude with your form :)

to simplify things, you might want to look into a good templating package..
I prefer smarty: http://smarty.php.net/ but there are other solutions that
do similar things. this allows you to simpllify the php code quite a bit,
and it is quite a bit easier to teach someone that knows HTML how to deal
with a 'template system' vs explaining how to use 'print' or 'echo'
statements to modify things. :)

also, I found it handy to put all the functions that deal with a particular
table into one php module, and then make calls into it via a GET request.

for example:

member.php might contain:

-- begin member.php --
class member
{
  function edit()
  {
    // I've snipped out the variable assignments from above.. you need to
    // make sure you assign something to $name and $address before trying to
    // use the template.

    $s = new Smarty;
    $s->assign("submitmode", "update");
    $s->assign("name", $name);
    $s->assign("address", $address);
    $s->display("member.tmpl");
  }

  function main()
  {
     $mode = $_REQUEST["mode"];
     // $mode = preparestring($mode);
     switch ($mode)
     {
        case "edit":
          $this->edit();
          break;
        default:
          print "unknown mode {$mode}";
          break;
     }
  }
}

$m = new member;
$m->main();
-- end member.php --

then, you make a 'member.tmpl' in the templates directory (see instructions
for smarty) that looks something like this:

-- begin member.tmpl --
<form method="POST" action="member.php">
<input type="hidden" name="mode" value="{$submitmode}">
<input type="text" name="name" value="{$name}">
</form>
-- end member.tmpl --

of course I have left out the submit button and some other fields for
simplicity, but you get the idea.

note the use of the 'hidden' field called 'mode', which will be processed by
the main() method in the member class instance.

what will happen in my example is that when the user clicks 'submit',
$mode will be equal to 'update', which you can detect by using a 'case'
statement. that means you can have as many 'mode's as you want, and you will
find that you use certain ones over and over and over again, so you can just
cut and paste and then adjust to the specific needs of the table in
question.

for example, I usually have 'add', 'insert', 'edit' and 'update' modes and
they all use the same template, just different values for 'submitmode'..  in
the specific case of 'add', you don't fill in values for anything except
submitmode, and leave the rest blank.

from the template, you can access any variable that has been 'assigned' to
the template object instance with assign(), and you quote things with curly
braces just like php suggests you do, which makes it really clear what is
going on without a lot of confusion. once you understand the technique, it
is simplicity itself.

when you want to have a link to 'add member' (aka "new user"), you do
something like:

http://localhost/member.php?mode=add

if you want to present the edit form, use:

http://localhost/member.php?mode=edit

note that 'update' and 'insert' are not normally given to the user as
choices, because they are used internally.. however, if you *want* to
automate a form submission (via a cronjob or whatever) you can do so quite
easily.. you just need to write something that will POST a form and as long
as you fill everything in (and especially mode), you can do it without fuss,
in any language you choose.

regards,
J
--
|| Jeff - http://zoidtechnologies.com/
|| GNUPG Fingerprint: A607 0F19 7C75 1305 67E4  BDFF 26BD 606E 3517 2A42

Re: PHP form Creates Blank DB entries

From
"philip johnson"
Date:
pgsql-php-owner@postgresql.org wrote:
> At 12:16 PM 6/30/03, Michael Hanna wrote:
>> // error checks on form submission go here
>> // generate and execute a query
>> $query = "INSERT INTO addressbook VALUES
>> (nextval('addressbook_id_seq'), '$name', '$address', '$tel',
>> '$email')"; $result = pg_query($connection, $query)
>>         or die("Error in query: $query. " .
>> pg_last_error($connection)); echo "Data successfully added.";
>> // close database connection
>> pg_close($connection); } ?>
>
>
> Probably because "register globals" is off (default changed since
>          4.2.0). http://ca3.php.net/register_globals
>
> Insert the following lines before "$query = ..." line:
>
> $name = $_POST[name];
> $address = $_POST[address];
> $tel = $_POST[tel];
> $email = $_POST[email];
>
>
>
> ---------------------------(end of
> broadcast)--------------------------- TIP 2: you can get off all
>     lists at once with the unregister command (send "unregister
> YourEmailAddressHere" to majordomo@postgresql.org)

you could you the following code :

if ( phpversion() >= "4.2.0") {
  foreach($_POST as $keys=>$values) {
     ${$keys}=$values;
  }
}
else {
  foreach($HTTP_POST_VARS as $keys=>$values) {
    ${$keys}=$values;
  }
}


Re: PHP form Creates Blank DB entries

From
Bruno Wolff III
Date:
On Mon, Jun 30, 2003 at 18:22:59 -0400,
  Jeff <jam@zoidtechnologies.com> wrote:
>
> also, I would suggest running each of the variables through a function that
> strips out html tags (since you don't really care about allowing them in
> this case, right?).. you can do that with strip_tags.. see
> http://php.net/strip_tags

Wouldn't it be better to replace <, >, " and & with <, >, " and
&, resprectively since those characters could legitimately appear
in at least some of those strings?

Re: PHP form Creates Blank DB entries

From
Jeff
Date:
On Tue, Jul 01, 2003 at 08:46:57AM -0500, Bruno Wolff III wrote:
> Date: Tue, 1 Jul 2003 08:46:57 -0500
> From: Bruno Wolff III <bruno@wolff.to>
> To: Jeff <jam@zoidtechnologies.com>
> Cc: Frank Bax <fbax@sympatico.ca>, pgsql-php@postgresql.org
> Subject: Re: [PHP] PHP form Creates Blank DB entries
> Mail-Followup-To: Jeff <jam@zoidtechnologies.com>,
>     Frank Bax <fbax@sympatico.ca>, pgsql-php@postgresql.org
>
> On Mon, Jun 30, 2003 at 18:22:59 -0400,
>   Jeff <jam@zoidtechnologies.com> wrote:
> >
> > also, I would suggest running each of the variables through a function that
> > strips out html tags (since you don't really care about allowing them in
> > this case, right?).. you can do that with strip_tags.. see
> > http://php.net/strip_tags
>
> Wouldn't it be better to replace <, >, " and & with <, >, " and
> &, resprectively since those characters could legitimately appear
> in at least some of those strings?

yes, preparestring handles not only the call to strip_tags, but a call to
htmlentities as well, which covers the above. I did not indicate this fact
clearly in my email-- I apologize for being misleading.

if I've missed anything, please let me know.. I think I have all the bases
covered, but I'm willing to make changes if there is some glaring hole (or
even a not-so-glaring one) I have missed :)

you can check the eros tarball, common.php, the function is called
preparestring.

regards,
J
--
|| Jeff - http://zoidtechnologies.com/
|| GNUPG Fingerprint: A607 0F19 7C75 1305 67E4  BDFF 26BD 606E 3517 2A42