PHP & MySQL storing multiple values in a database
I'm basically a front end designer and new to PHP and MySQL but I want a user to be able to store multiple names and there meanings in a MySQL database table named names
using PHP I will dynamically create form fields with JQuery every time a user clicks on a link so a user can enter 1 to 1,000,000 different names and there meanings which will be stored in a table called names
.
All I want to know is how can I store multiple names and there meanings in a database and then display them back to the user for them to edit or delete using PHP & MySQL?
I created the MySQL table already.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
Here is the HTML.
<form method="post" action="index.php">
<ul>
<li><label for="name">Name: </label><input type="text" name="name" id="name" /></li>
<li><label for="meaning">Meaning: </label><input type="text" name="meaning" id="meaning" /></开发者_如何学编程li>
<li><input type="submit" name="submit" value="Save" /></li>
</ul>
</form>
If you use
<input name="myfield[]">
then you can repeat this element multiple times and in PHP you will get an array with all the values.
Instead of myfield, you can use any name. Just make sure you append the "[]" at the end.
You would somehow create an array of name
and meanings
out of the POST
data, then run it through something like:
// Assuming count($name) == count($meaning)
for($i = 0; $i < count($name); $i++)
{
$sql = "INSERT INTO `names` (`id`, `userID`, `name`, `meaning`) VALUES('', '', '".$name[$i]."', '".$meaning[$i]."');";
mysql_query($sql);
}
Note that since there is user input the arrays should be escaped with addslashes
when creating them.
精彩评论