I’m new to PHP and MySQL and I’m trying to store a users entered data from the following fields $skill, $experience, $years which a user can also add additional fields of $skill, $experience, $years if needed so in instead of 1 of each field there might be multiples of each field.
I was wondering how can I store the fields in my MySQL database using PHP and MySQL? I have the following script but I know its wrong. can some one help me fix the script listed below?
Here is the PHP and MySQL code.
$skill = serialize($_POST['skill']);
$experience = serialize($_POST['experience']);
$years = serialize($_POST['years']);
for (($s = 0; $s < count($skill); $s++) && ($x = 0; $x < count($experience); $x++) && ($g = 0; $g < count($years); $g++)){
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$query1 = "INSERT INTO learned_skills (skill, experience, years) VALUES ('" . $skill[$s] . "', '" . $experience[$x] . "', '" . $years[$g] . "')";
if (!mysqli_query($mysqli, $query1)) {
print mysqli_error($mysqli);
return;
}
}
Here is my MySQL table.
CREATE TABLE learned_skills (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
skill TEXT NOT NULL,
experience TEXT NOT NULL,
years INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE u_skills (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
skill_id INT UNSIGNED NOT NULL,
users_id INT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
You would create two tables that have a 1 to many relationship:
This way a user can have any number of listed skills. If skill is really just a small text string (like “PHP” or “MySQL”) then you should use a VARCHAR type instead of TEXT. If that’s the case, once you get going you’ll see that it would be better to create a list of skills that the user can choose from and just have a skill_id rather than a text field. This helps with something called normalization (a way to prevent duplicate data).
Good luck in your learning.