Jump to content

Need help with an account update snippet


baser-b

Recommended Posts

I really swear that the host I use is like screwing with me hard. Like literally will have something working one night, wake up the next day to my error log full and nothing working anymore. Or, like in this case, have the code working fine, perfectly in fact, to all of the sudden bring up all these errors and shit without changing anything I just can't figure it out.

Point being, I am working on this portal, and on the account page, you can update your info. Which for one field...

$result = queryMysql("SELECT * FROM accounts WHERE user='$user'");
   $row = $result->fetch_assoc();
$set_comp  = $row['company'];

// Check if 'Company' value is set
   if (isset($_POST['company']))
   {
      $company = sanitizeString($_POST['company']);

      if ($_POST['company'] != $set_comp)
      {
         queryMysql("UPDATE accounts SET company='$company' WHERE user='$user'");
      }
         elseif ($set_company == "")
	     {
	        queryMysql("INSERT INTO accounts (company) VALUES('$company') WHERE user='$user'");
		 }
		 elseif (empty($_POST['company']))
		 {
			$company = "";
		 }
            else 
		    {
			   $company = stripslashes($row['company']);
		    }

   }   

And the form...

Quote

<form method='post' action='account.php' enctype='multipart/form-data'>
Company:</th><td><input type='company' size='50' maxlength='40' name='company' value='$company'>
<input type='submit' value='Save Info'>
</form>

 

Now before it inexplicably stopped working, what it was doing and meant to do was display a form, that either had the information that was set, or displayed nothing because nothing was entered, and you could either put something there or change what was already there. Now it keeps telling me:

[22-Oct-2018 06:29:37 UTC] PHP Notice:  Undefined variable: company in /home/iqy0804tq6fq/public_html/portal/account.php on line 262

Also, sanitizeString and queryMysql are my own created functions, they work fine. I tried removing the elseif (empty($_POST['company'])), and just left the last else in, didn't work. It just displays empty columns now. Now also, when I try to update, it feeds me all these errors now my SQL syntax is wrong its LIKE HOW DID THIS CHANGE IN 10 SECONDS!!? I didn't DO anything for my syntax to be any different than when it worked perfectly! It's insanity.

Link to comment
Share on other sites

All that logic you have to set $company only happens if the form was submitted. Which won't happen on the first page load. Alter the code so that $company is always set, even if the form has not been submitted yet.

As for your hosting provider... not sure I can help you there. If you don't make any changes to your site at all, and doing the exact same thing gives different results (eg, error messages when there weren't before) then you should talk to the host to see what they're doing.

Worst case you dump them and move to someone else.

Link to comment
Share on other sites

this code is filled with mistakes (the incorrect INSERT query, a form field type = 'company', a changing/non-existent variable name) and the symptom of it seemingly working at one point, then not at another, is due to some of those mistakes and the changing data being tested that doesn't mean what you think. by testing for an empty string '""/empty() in the logic, you cannot tell if the data exists but is empty or if the data doesn't exist at all.

the way to initially SELECT and retrieve data to be edited is to define an empty array variable, $post for example, before the start of the form processing code, copy the submitted form data to this variable inside of the form processing code, then after the end of the form processing code, if the variable is empty query for and retrieve the existing data and assign it to this variable. use the contents of this variable when outputting the values in the form fields.

next, if the accounts db table is the primary user table, i.e. a row will exist if the user exists, then the only query in this edit form processing code should be one UPDATE query (i suspect you have repeated this code and query for each form field.) if this is instead an add-on db table, designed only to hold profile information, where there many not initially be a row for any user, than the query you have in this edit form processing code should be one INSERT ... ON DUPLICATE KEY UPDATE ... query, with the user_id being defined as the unique key that triggers the duplicate key part.

your form processing code should also validate the submitted data, storing validation errors in an array variable, then only use the submitted data if it is valid. if you have repeated the posted code/query(ies) for each form field, you should instead just have one consolidated form processing code with one query that operates on all the form fields at once.

you should also use prepared queries when supplying data to an sql query statement (no matter how good you think your sanitizeString() function is, there are hackers out there with libraries of injectable sql that can probably get past it, especially if you have not set the character set that php is using to match your database, and you should only apply any sort of sql protection to the data being supplied to a query, not to data that is being output in form field values and you shouldn't be trying to strip slashes and certainly not from data after you have retrieved it from your database.) 

 

Link to comment
Share on other sites

  • 4 weeks later...

So I tried to do the thing of running through the values in the $_POST and comparing them to etc etc. Anyway, this is what I came up with, which doesn't work.


   if (isset($_POST['save']))
   {
      foreach ($_POST as $key => $value)
      {
         foreach ($row as $rkey => $rvalue)
	 { 
	    if (array_search($key, $rkey))
	    {
               if($rkey == "email")
               {
	          if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	          {
                     $error = "Invalid email format.";
	          }
	       }
	       if ($rkey == "website")
               {
	          if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
                  {
                     $error = "Invalid URL.";
                  }
               }
               if ($rvalue != $value)
               {
	          queryMysql("UPDATE accounts SET $rkey='$value' WHERE user='$user'");
                  $info = "$rkey updated.";
               }
                  else
                  {
                     queryMysql("INSERT INTO accounts ($rkey) VALUE('$value') WHERE user='#user'");
                     $info = "$rkey updated.";
                  }
            }  
         }
      }

 

Link to comment
Share on other sites

6 minutes ago, baser-b said:

queryMysql("INSERT INTO accounts ($rkey) VALUE('$value') WHERE user='#user'");

Probably a waste of time commenting (you don't seem to read replies) but an INSERT query can not have a WHERE clause.

 

8 minutes ago, baser-b said:

WHERE user='#user'

And did you really mean "#user"?

Link to comment
Share on other sites

Okay, so this is the code I came up with mac_gyvers suggestions. It should be remembered (though how could you forget?) that I am a moron and also very new to PHP but am trying my best to learn.

   if (isset($_POST['save']))
   {
      foreach ($_POST as $key => $value)
      {
         foreach ($row as $rkey => $rvalue)
	     { 
	        if (array_search($key, $rkey))
	        {
              if($rkey == "email")
              {
	             if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	             {
                    $error = "Invalid email format.";
	             }
	          }
	          if ($rkey == "website")
              {
	             if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
                 {
                   $error = "Invalid URL.";
                 }
              }
              if ($rvalue != $value)
              {
	              queryMysql("UPDATE accounts SET $rkey='$value' WHERE user='$user'");
                  $info = "$rkey updated.";
               }
            }
         }
      }
   }

 

Link to comment
Share on other sites

$result = queryMysql("SELECT * FROM accounts WHERE user='$user'");
   $row = $result->fetch_array();
   
       $pass  = $row['pass'];
       $fname    = $row['fname'];
       $lname    = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $title = $row['title'];
       $company  = $row['company'];
       $website  = $row['website'];
       $snailmail = $row['snailmail'];

   if (isset($_POST['save']))
   {
      if (array_diff_assoc($_POST, $row));
      {
         foreach (_$POST as $key => $value)
         {
            if ($key == $row[$key])
            {
               queryMysql("UPDATE accounts SET " . $row[$key] . "='$value' WHERE user='$user'")
            }
         }
   }

This is a different version I wrote that makes more sense. Though it returns: PHP Parse error:  syntax error, unexpected '$POST' (T_VARIABLE)

Edited by baser-b
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.