views:

345

answers:

2

I want to use temporary tables in my PHP code. It is a form that will be mailed. I do use session variables and arrays but some data filled in must be stored in a table format and the user must be able to delete entries in case of typos etc. doing this with arrays could work (not sure) but I'm kinda new at the php and using tables seems so much simpler. My problem is that using mysql_connect creates the table and adds the line of data but when i add my 2nd line it drops table and create it again... Using mysql_pconnect works by not dropping the table but creates more than on instance of the table at times and deleting entry's? what a mess! How can I best use temporary tables and not have them droped when my page refreshes? not using temporary tables may cause other issues if the user closes the page and leaving the table in the database.

+1  A: 

Sounds like a mess! I am not sure why you are using a temp table at all, but you could create a random table name and assign it to a session variable. But this is hugely wrong as you would have a table for each user!

If you must use a database, add field to the table called sessionID. When you do your inserting/deleting reference the php sessionid.

Just storing the data in the session would probably be much easier though...

Byron Whitlock
+1 to suggestion of using a session for "unfinished" data.
Bill Karwin
+1  A: 

Better to create a permanent table and temporary rows. So, say you've serialized the object holding all your semi-complete form data as $form_data. At the end of the script, the last thing that should happen is that $form_date should be stored to the database and the resulting row id be stored in your $_SESSION. Something like:

$form_data=serialize($form_object); //you can also serialize arrays, etc.
//$form_data may also need to be base64_encoded

$q="INSERT INTO incomplete_form_table(thedata) '$form_data'";    
$r=mysqli->query($q);
$id=$mysql->last_insert_id;
$_SESSION['currentform']=$id;

Then, when you get to the next page, you reconstitute your form like this:

$q="SELECT thedata FROM incomplete_form_table WHERE id={$_SESSION['currentform']}";
$r=$mysql->query($q);
$form_data=$r->fetch_assoc();
$form=$form_data['thedata'];//if it was base64_encoded, don't forget to unencode it first

You can (auto-) clean up the incomplete_form_data table periodically if the table has a timestamp field. Just delete everything that you consider expired.

The above code has not been exhaustively checked for syntax errors.

dnagirl
Thanks for the feedback I'm gonna give this a try.
duncan