Hello Krik, thank you for helping me.

I shortened the code for the post (as you probably guessed) and obviously failed.

Heres the full php code:

<?php

if(!$userID) echo 'not logged in (line 3)';

else {

echo '<div id="tabs">

  <ul>
  <li>(not important)</li>
  </ul>

  </div>
  <div class="webspell-head"></div>

  <table width="100%" border="0">
     <tr>
       <td>(not important)</td>
     </tr>
  </table>';

if(isset($_POST['submit'])) {
// mushroom cup
		$LC_m = $_POST['LC_m'];
		$LC_s = $_POST['LC_s'];
		$LC_ms = $_POST['LC_ms'];

	$id = $userID;

	if(isset($_POST['userID']) or isset($_GET['userID']) or $userID=="") die('not logged in (line 140)');

	$LC = $LC_m.'.'.$LC_s.'.'.$LC_ms;

    safe_query("UPDATE `".PREFIX."timetrials`
					SET 
						LC='".$LC."',
					WHERE 
						userID='".$id."'");

		redirect("index.php?site=tt_my_times&amp;id=$id", 'Times updated',3);
}

else {
      $ergebnis = safe_query("SELECT * FROM ".PREFIX."timetrials WHERE userID='".$userID."'");
      $anz = mysql_num_rows($ergebnis);

      if($anz) {
        $ds = mysql_fetch_array($ergebnis);

        $LC_m = mb_substr($ds['LC'],0,1);
        $LC_s = mb_substr($ds['LC'],2,2);
        $LC_ms = mb_substr($ds['LC'],5,3);
      }
        eval("\$tt_update = \"".gettemplate("tt_update")."\";");
        echo $tt_update;
 }
}
?>

'PREFIX' is defined within a seperate file called '_mysql.php':

<?php
	 $host = "localhost";
	 $user = "username";
	 $pwd = "password";
	 $db = "db_name";
	 define("PREFIX", 'ws_rv_');
	?>

'safe_query' is defined within '_functions.php':

// -- MYSQL QUERY FUNCTION -- //
$_mysql_querys = array();
function safe_query($query="") {
	global $_mysql_querys;
	if(stristr(str_replace(' ', '', $query), "unionselect")===FALSE AND stristr(str_replace(' ', '', $query), "union(select")===FALSE){
		$_mysql_querys[] = $query;
		if(empty($query)) return false;
		if(DEBUG == "OFF") $result = mysql_query($query) or die('Query failed!');
		else {
			$result = mysql_query($query) or die('Query failed: '
			.'<li>errorno='.mysql_errno()
			.'<li>error='.mysql_error()
			.'<li>query='.$query);
		}
		return $result;
	}
	else die();
}

(unless I'm mistaken).

    In my previous post I think I got lost in jungle of your code and didn't realize what you wanted.

    The new page is basically a submission form which sends data to the database

    That sound like an "INSERT INTO".

    safe_query("UPDATE `".PREFIX."timetrials`
                            SET
                                LC='".$LC."',
                            WHERE
                                userID='".$id."'");
    

    But you're trying to "UPDATE". Update is for changing an existing record.

    I would note that if your debugging is on

    if(DEBUG == "OFF")
    

    It would have told you something to that effect.

      lol sorry about the jungle.

      Yes it submits information, but it should also update the information if it already exists.

      I'll try INSERT INTO now, thank you 🙂

        error=You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE userID='1'' at line 35

        😐

          INSERT queries don't have a WHERE clause (it wouldn't make sense if they did).

            INSERT INTO would create a new row everytime anyway (thats not what I want).

            Users are submitting information (the first time) and updating it from then onwards.

              Users are submitting information (the first time) and updating it from then onwards.

              Let clarify that statement. Is the form going to do both?

              So a new user comes to your form page enters their info and clicks submit and the system adds a new record to the database. And then if the same user need to change it they use the same form but now you just need it to update the record.

              Is that what you're going to have happen?

                Yes, thats exactly what I would like.

                  Then somehow your code needs to be told or be able to find out which is the case.

                  Now I do see that your code is checking for a the "userID", but currently your code is set to "die" if the "userID" is set or it is blank. That is definitely not what you want.

                  if(isset($_POST['submit'])) {
                  // mushroom cup
                  	$LC_m = $_POST['LC_m'];
                  	$LC_s = $_POST['LC_s'];
                  	$LC_ms = $_POST['LC_ms'];
                  
                  $id = $userID;
                  
                  $LC = $LC_m.'.'.$LC_s.'.'.$LC_ms;
                  
                  if (isset($_REQUEST['userID'])) {
                  	safe_query("
                  		UPDATE `".PREFIX."timetrials`
                  		SET LC='".$LC."',
                  		WHERE userID='".$id."'
                  	");
                  }
                  else {
                  	safe_query("
                  		INSERT INTO `".PREFIX."timetrials` (`LC`)
                  		VALUE ('" . $LC . "')
                  	");
                  }
                  redirect("index.php?site=tt_my_times&amp;id=$id", 'Times updated',3);
                  }
                  

                  Note that I only am checking REQUEST as that will check both POST and GET for the "userID" index.

                  EDIT: Looking at that a second time, now, I am not sure if you will want to do the check via the "userID" I am guessing both it insert and to update will require the user to be logged in. So you may need to find some other way to determine if the record needs to be inserted or updated.

                    Krik, thank you so much, finally after a week of bashing my head against the keyboard it's working! lol.

                    I have more than one field though (32 to be exact) so would it be:

                    	else {
                            safe_query("
                                INSERT INTO `".PREFIX."timetrials` (`LC`)
                                VALUE ('".$LC."')
                            ");
                    
                     safe_query("
                                INSERT INTO `".PREFIX."timetrials` (`LC2`)
                                VALUE ('".$LC2."')
                            ");
                        }

                    (and so on..)

                    or is there a quicker way?

                      Krik;10962491 wrote:

                      EDIT: Looking at that a second time, now, I am not sure if you will want to do the check via the "userID" I am guessing both it insert and to update will require the user to be logged in. So you may need to find some other way to determine if the record needs to be inserted or updated.

                      Thats fine, I want it so that the user must be logged in to insert/update.

                        Sorry for triple post, I cant edit my own posts.

                        Krik, now when I update it creates a new row/record with a new ID, instead of updating the existing record.

                        argh.

                          Whats happening:

                          1. Enter data, gets added to db under userID 1.
                          2. Form shows the data.
                          3. Update the data, gets added to db under userID 2.
                          4. Form shows data for userID 1.

                            3. Update the data, gets added to db under userID 2.
                            4. Form shows data for userID 1.

                            The one thing your code doesn't display is how the system determines which user is submitting the data. I see the "$userID" variable but I don't see where it is set So you need to first make sure that the "$userID" is being set correctly as it is very key in getting everything to work.

                            I have more than one field though (32 to be exact) ...

                                else {
                                    safe_query("
                                        INSERT INTO `".PREFIX."timetrials` (`LC`, `LC2`)
                                        VALUE ('" . $LC . "', '" . $LC2 . "')
                                    ");
                                }
                            
                              Krik;10962510 wrote:

                              The one thing your code doesn't display is how the system determines which user is submitting the data. I see the "$userID" variable but I don't see where it is set So you need to first make sure that the "$userID" is being set correctly as it is very key in getting everything to work.

                              This was what I was thinking, but I was under the impression that $userID was some kind of universal string (like $GET or something) or was being pulled from somewhere automatically as part of the overall site mechanics (functions.php or _settings.php).

                              Ok I'm going to try and explain completely (god help us all):

                              The code you see here is a modified version of a different file (myprofile.php) whereby users submit information (such as 'nickname', 'about me' etc). It's then stored within a table called 'ws_rv_user' under a row assigned to their userID (which I assume is automatically allocated when a user registers).

                              Everywhere else throughout the site where users submit other information (mygalleries, myvideos etc) the data gets stored under the same userID. So for example, if you were the 9th user to register with the site, your userID will be 9 and within ws_rv_galleries and ws_rv_videos db tables, your pictures/videos are stored under your userID (9).

                              I'm trying to add my own extension to the site (mytimetrials) using the same system. I'm using virtually the exact same code of myprofile.php, but for some reason the data isn't getting stored. I understand that there isn't an 'INSERT INTO' command in this code, but then there isn't any 'INSERT INTO' command for the original myprofile.php file I edited. I checked the register.php file to see if that was using 'INSERT INTO' to create the initial db table rows and it does:

                              // insert in db
                              			$md5pwd = md5(stripslashes($pwd1));
                              			$registerdate=time();
                              			$activationkey = createkey(20);
                              			$activationlink='http://'.$hp_url.'/index.php?site=register&key='.$activationkey;
                              
                              		safe_query("INSERT INTO `".PREFIX."user` (`registerdate`, `lastlogin`, `username`, `password`, `nickname`, `email`, `newsletter`, `activated`) VALUES ('$registerdate', '$registerdate', '$username', '$md5pwd', '$nickname', '$mail', '1', '".$activationkey."')");
                              
                              		$insertid = mysql_insert_id();
                              
                              		// insert in user_groups
                              		safe_query("INSERT INTO ".PREFIX."user_groups ( userID ) values('$insertid' )");

                              So I presume I cant use UPDATE since there is no row created within ws_rv_timetrials for that user yet? but myprofile.php does add data to the table which wasn't 'inserted':

                              	if(isset($_POST['submit'])) {
                              
                                          $nickname = htmlspecialchars(mb_substr(trim($_POST['nickname']), 0, 30));
                              	if(isset($_POST['mail'])) $mail = $_POST['mail'];
                              	        else $mail="";
                              	if(isset($_POST['mail_hide'])) $mail_hide = true;
                              	else $mail_hide = false;
                              	$usernamenew = mb_substr(trim($_POST['usernamenew']), 0, 30);
                              	$usertext = $_POST['usertext'];
                              	$firstname = $_POST['firstname'];
                              	$lastname = $_POST['lastname'];
                              	$b_day = $_POST['b_day'];
                              	$b_month = $_POST['b_month'];
                              	$b_year = $_POST['b_year'];
                              	$sex = $_POST['sex'];
                              	$flag = $_POST['flag'];
                              	$about = $_POST['messageabout'];
                                          $clantag = $_POST['clantag'];
                              	$clanname = $_POST['clanname'];
                              	$clanhp = $_POST['clanhp'];
                              	$connection = $_POST['connection'];
                              	$cpu = $_POST['cpu'];
                              	$graphiccard = $_POST['graphiccard'];
                              	$mainboard = $_POST['mainboard'];
                              	$ram = $_POST['ram'];
                              	$soundcard = $_POST['soundcard'];
                              	$town = $_POST['town'];
                                          $browser = $_POST['browser'];
                                          $fc = $_POST['fc'];
                                          $fcalt = $_POST['fcalt'];
                                          $gamertag = $_POST['gamertag'];
                                          $joined = $_POST['joined'];
                                          $miinames = $_POST['miinames'];
                                          $os = $_POST['os'];
                                          $psn = $_POST['psn'];
                                          $skype = $_POST['skype'];
                                          $stream = str_replace('http://', '', $_POST['stream']);
                                      $userquote = $_POST['userquote'];
                                          $youtube = str_replace('http://', '', $_POST['youtube']);
                              	$newsletter = $_POST['newsletter'];
                              	$homepage = str_replace('http://', '', $_POST['homepage']);
                              	$pm_mail = $_POST['pm_mail'];
                              	$avatar = $_FILES['avatar'];
                              	$userpic = $_FILES['userpic'];
                              	$language = $_POST['language'];

                              So I gather once the initial table row is inserted, columns/fields are easier to add, and you cant add fields until a row has been inserted? anyway, I noticed in the galleries.html file this:

                              <input type="hidden" name="userID" value="'.$userID.'">

                              And in myvideos.php this:

                              <input type="hidden" name="uploader" value="'.$userID.'">

                              So perhaps something like this is what I'm missing to tell the timetrials db table my correct userID (but I still need to insert the row).

                              mygalleries.php builds its row like this:

                              if(isset($_POST['saveedit'])) {
                              
                              include('_mysql.php');
                              include('_settings.php');
                              include('_functions.php');
                              
                              $_language->read_module('gallery');
                              
                              $galclass = new Gallery;
                              
                              $ds = mysql_fetch_array(safe_query("SELECT galleryID FROM ".PREFIX."gallery_pictures WHERE picID='".$_POST['picID']."'"));
                              
                              if((isgalleryadmin($userID) or $galclass->isgalleryowner($ds['galleryID'], $userID)) and $_POST['picID']) {
                              
                              	safe_query("UPDATE ".PREFIX."gallery_pictures SET name='".$_POST['name']."', comment='".$_POST['comment']."', comments='".(int)$_POST['comments']."' WHERE picID='".$_POST['picID']."'");
                              	if(isset($_POST['reset'])) safe_query("UPDATE ".PREFIX."gallery_pictures SET views='0' WHERE picID='".$_POST['picID']."'");
                              
                              }
                              else redirect('index.php?site=gallery', $_language->module['no_pic_set']);
                              
                              redirect('index.php?site=gallery&amp;picID='.$_POST['picID'], '', 0);
                              
                              }

                              Again, no INSERT command, and this is one of the original Webspell files.

                              myvideos.php uses actions:

                              elseif($_POST["save"]) {
                              	$movscreenshot=$_FILES["movscreenshot"];
                              	$movheadline=$_POST["movheadline"];
                              	$movfile=$_POST["movfile"];
                              	$movdescription=$_POST["movdescription"];
                              	$movcatID=$_POST["movcatID"];
                              	$uploader=$_POST["uploader"];
                              	$embed=$_POST["embed"];
                              
                              echo'
                              	<h2>'.$_language->module['movies'].'</h2>';
                              
                              if($movheadline AND ($movfile OR $embed)) {
                              	if(eregi('http://', $movfile)) $movfile=$movfile;
                              	else $movfile='http://'.$movfile;
                              
                              	safe_query("INSERT INTO ".PREFIX."movies (movID, activated, embed, uploader, movheadline, movfile, movdescription, date, movcatID) values('', '".$admin_activation."', '".$embed."', '".$uploader."', '".$movheadline."', '".$movfile."', '".$movdescription."', '".time()."', '".$movcatID."')");
                              	$id=mysql_insert_id();
                              
                              	if($movscreenshot[name]!="") {
                              	$file_ext=strtolower(substr($movscreenshot[name], strrpos($movscreenshot[name], ".")));
                              	if($file_ext==".gif" OR $file_ext==".jpg" OR $file_ext==".png") {
                              		if($movscreenshot[name] != "") {
                              			move_uploaded_file($movscreenshot[tmp_name], $filepath.$movscreenshot[name]);
                              			@chmod($filepath.$movscreenshot[name], 0755);
                              			$file=$id.$file_ext;
                              			rename($filepath.$movscreenshot[name], $filepath.$file);
                              			if(safe_query("UPDATE ".PREFIX."movies SET movscreenshot='".$file."' WHERE movID='".$id."'")) {
                              				redirect("index.php?site=myvideos", "".$_language->module['vid_created'].".", "3");
                              			} else {
                              				redirect("index.php?site=myvideos", "".$_language->module['screen_error'].".", "3");
                              			}
                              		}
                              	} else echo'<b>'.$_language->module['screen_error1'].'</b><br><br><a href="javascript:history.back()">&laquo; '.$_language->module['back'].'</a>';
                              	}
                              	redirect("index.php?site=myvideos", "".$_language->module['mov_added']."!", "3");
                              } else echo'<b>'.$_language->module['form_error'].'</b><br><br><a href="javascript:history.back()">&laquo; '.$_language->module['back'].'</a>';
                              }

                              (this was an addon and isn't an original Webspell file).

                              As I said, both of these store data under the same userID allocated to users upon registration.

                                  else {
                                      safe_query("
                                          INSERT INTO `".PREFIX."timetrials` (`LC`, `LC2`)
                                          VALUE ('" . $LC . "', '" . $LC2 . "')
                                      ");
                                  }
                              

                              Thank you my friend.

                              Sorry for another jungle of code.

                                $userID is not a superglobal like $_GET. It is an ordinary variable that must be set somewhere.

                                was being pulled from somewhere automatically as part of the overall site mechanics (functions.php or settings.php).

                                This is very likely, I do this with many of my sites where I have the user id variable set in a file that is included in all pages. If this is the case for you then you must include those files in any new pages you make if you wish to be able to access the $userID variable.

                                So I presume I cant use UPDATE since there is no row created within ws_rv_timetrials for that user yet?

                                Yep the row has to exist before you can update it

                                mygalleries.php builds its row like this:

                                if(isset($_POST['saveedit'])) {
                                ....
                                

                                The "saveedit" is telling the script that the user is editing the data. I have done this many times were I change the buttons "name" attribute if the user is updating verses adding new content. So if the "saveedit" was, for example, "savenew" what would php do? In the code you have, probably nothing. But it takes a minute to make it do something. PHP relies entirely on what you tell it and "savenew" can be an entirely different message than "saveedit", if you want it to.

                                As I said, both of these store data under the same userID allocated to users upon

                                This is common, in all the sites that I have users signing up on, once the user logs in, I keep track of the users id and then any thing they do (save, edit, act maliciously) I use there id to associate it with that action.

                                I didn't see any direct questions in your post so hopefully you have it figured out.

                                  Hello Krik,

                                  Yes I finally figured it out after a week of headaches. I couldn't of done it without your help Krik, I'm very greatful - thank you 🙂

                                  What I did was add a line to the register.php file:

                                  	$insertid = mysql_insert_id();
                                  
                                  	// insert in user_groups
                                  		safe_query("INSERT INTO ".PREFIX."user_groups ( userID ) values('$insertid' )");
                                  
                                  	// insert in timetrials
                                  		safe_query("INSERT INTO ".PREFIX."timetrials ( userID ) values('$insertid' )");

                                  It's not a complete solution since it will only work for new users but I'm lucky because it's a new site and currently I'm the only user.

                                  I do have a next question though...

                                  How could I add a record of the date when a field was last updated? (if it isn't already recorded somewhere and I dont know about it).

                                  I have 32 fields:

                                          safe_query("
                                              UPDATE `".PREFIX."timetrials`
                                  						SET 
                                  							LC='".$LC."',
                                  							MMM='".$MMM."',
                                  					    	        MG='".$MG."',
                                  							TF='".$TF."',
                                  							MC='".$MC."',
                                  							CM='".$CM."',
                                  							SBX='".$SBX."',
                                  							WGM='".$WGM."',
                                  							DC='".$DC."',
                                  							KC='".$KC."',
                                  							MT='".$MT."',
                                  							GV='".$GV."',
                                  							DDR='".$DDR."',
                                  							MH='".$MH."',
                                  							BC='".$BC."',
                                  							RR='".$RR."',
                                  							PB='".$PB."',
                                  							YF='".$YF."',
                                  							GV2='".$GV2."',
                                  							MR='".$MR."',
                                  							SL='".$SL."',
                                      						        SGB='".$SGB."',
                                  							DS='".$DS."',
                                  							WS='".$WS."',
                                  							DH='".$DH."',
                                  							BC3='".$BC3."',
                                  							JP='".$JP."',
                                  							rMC='".$rMC."',
                                  							MC3='".$MC3."',
                                  							PG='".$PG."',
                                  							DKM='".$DKM."',
                                       						        rBC='".$rBC."'
                                  		    			        WHERE 
                                  			    			        userID='".$id."'");

                                  When the data for each field is displayed (on the site) I would also like to display the date that field was last updated.

                                  I imagine I need to create 32 fields to store the date? but how would the date be added to those fields?

                                  Thanks again, I will have to buy you a drink 😉

                                    Wow, I don't think you know what you just asked. I am going to explain how you can but you may get lost along the way.

                                    First you should find some articles on multidimensional databases. You need to understand the concept as what follows will rely on you knowing it at least the basics. The first one I read on the topic years ago was on PHP builder but I can not find it now. But there are plenty of them out there.

                                    The concept of multidimensional databases is like assigning 2 or more columns names to a field. But it is bit more complicated than that.

                                    Now the best way to be able to store the date and time each record was updated is to have each record stored in its own row. That means 32 rows for each user in the "timetrials" table. Now your brain may be spinning as to how that is going to work.

                                    You will have to associate each record in the "timetrials" table with data in other tables. Like all the 32 records, for a user, will also need to have the users id assigned to them. Also all 32 rows, for a user, will need to have some way of distinguishing which row is for which time trial.

                                    So first you going to have to completely redo your "timetrials" table. I would say make it have only 5 columns; unique id, user id, field id, field data, and time stamp. Think of it as rotating the table 90 degrees and then adding a column name may help you visualize this a bit.

                                    The table will look something like this then

                                    unique_id | user_id | field_id | field_data | time_stamp
                                         1    |   101   |    24    | 05.32.346  | 2010-08-22 08:39:51
                                         2    |   101   |     2    | 02.16.009  | 2010-08-27 14:02:36
                                         3    |   101   |    15    | 10.55.874  | 2010-09-01 20:54:01
                                    

                                    The field_ id represent the the old column names, to make those numeric values mean something you will want to create a new table that will store all 32 fields names with a unique id for each field name. This will allow you to associate a name with each data set but without having into enter the name over an over again. The big advantage with this is if after you have a couple hundred users if you need to change a fields name you will not need to manually change every place that names is used the "timetrials" table. Also if you need to add a new time trial you just edit the new table to add the 33rd field name and when teh users come to update the new record is added to the timetrials table.

                                    Now each user will end up having 32 rows in the "timetrials" table that are associated with them. So to retrieve all the time trials for a user you use a query something like this

                                    $qry = "
                                    	SELECT *
                                    	FROM `".PREFIX."timetrials`
                                    	LEFT JOIN ".PREFIX."user ON ".PREFIX."user.userID = `".PREFIX."timetrials`.user_id
                                    	LEFT JOIN ".PREFIX."fieldnames ON ".PREFIX."fieldnames.unique_id = `".PREFIX."timetrials`.field_id
                                    	WHERE `".PREFIX."timetrials`.`user_id` = '$userID'
                                    ";
                                    
                                    mysql_query($qry)
                                    

                                    At this point I am bit hesitant to go much further explaining how it all works. That is the basics, but I am afraid it may all go right over you head and just confuse you. One of the biggest problems is your tying this into a current system so who knows what other factors need to be taken into account to make all that work.

                                    If you wish to pursue doing this, that is fine just you will need to be able to take a solution and evaluate it based on the entire architecture of the system you have and modify it to fit in with that system.

                                      Oh wow... I feel bad now because I've taken so much of your time (sorry).

                                      I had no idea it would be so complicated - well perhaps not so complicated, but a lot of work.

                                      I dont know if all that work is worth it but if I do choose to implement it, atleast I know where to start, so thank you once again Krik.

                                        19 days later
                                        Krik;10962681 wrote:

                                        Now each user will end up having 32 rows in the "timetrials" table that are associated with them. So to retrieve all the time trials for a user you use a query something like this

                                        $qry = "
                                        	SELECT *
                                        	FROM `".PREFIX."timetrials`
                                        	LEFT JOIN ".PREFIX."user ON ".PREFIX."user.userID = `".PREFIX."timetrials`.user_id
                                        	LEFT JOIN ".PREFIX."fieldnames ON ".PREFIX."fieldnames.unique_id = `".PREFIX."timetrials`.field_id
                                        	WHERE `".PREFIX."timetrials`.`user_id` = '$userID'
                                        ";
                                        
                                        mysql_query($qry)
                                        

                                        Could you give me the query on how the update would be performed please?

                                        Thanks Krik.