Array to Database? Should I use serialize?
I have small expanding script that allows for up to 3 additional input fields:
The form portion:
<div id="dynamicInput">Uniform Resource Locator 1:<br><input type="text" name="myInputs" id="myInputs" placeholder="http://www.mydomainname.com">
<input type="button" class="add-more" value="Add Additional URL's / Domains" onClick="addInput('dynamicInput');">
The script portion:
var new_field = '<textarea name="myInputs"></textarea>';
The database portion:
$sql_insert = "INSERT into `users`
Im trying to work with an array of inputs and add the inputs to my users table. But I'm not sure if I should should use serialize for this or work with the "myInputs" array. How would I work with the array in this fashion?
I would not serialize() the inputs, as that makes it very difficult to do anything with it from a database standpoint, other than retrieving it so that you can use the array within your application code. The precise mechanics of how I'd put it in the query would depend in part on which database extension you are using, e.g. whether you can use prepared statements as with the PDO or MySQLi extensions, or using mysql_real_escape_string() with the older (and deprecated) MySQL extension, and so forth.
I am a big user of serializing to store in MySQL.
However I have learned that it is best really for fixed data, say backing up an exported excel spreadsheet generated by a website.
For small arrays, I far and away prefer to store it as a string.
This is because it allows me to still use built in sql functions
It also allows me to make quick changes or searchs from something like phpmyadmin
So my friend, I would suggest that you look heavily at explode and implode to store arrays, including multidimensional and associative arrays.
Or you could look into normalizing your data instead of cramming multiple data elements into a single data field. To be "1st normal form" compliant, those multiple, similar inputs should be in a separate table, each in a separate row with a column that points to the primary key of the "users" table, something like:
Now you can pull them in with the user data whenever you want them with a JOIN or LEFT JOIN in your SQL, and if you ever decide to change the number of links a user can submit, no changes are needed to the database, just to your application logic.
user_id (or whatever the primary key column is for users?)
link (probably a varchar field?)
Normalize! Normalize! Normalize!
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread