Home >Backend Development >PHP Tutorial >PHP MySQL Insert Into usage

PHP MySQL Insert Into usage

WBOY
WBOYOriginal
2016-07-25 08:55:011030browse
  1. $con = mysql_connect("localhost","peter","abc123");

  2. if (!$con)
  3. {
  4. die('Could not connect: ' . mysql_error());
  5. }

  6. mysql_select_db("my_db", $con);

  7. mysql_query("INSERT INTO Persons (FirstName, LastName, Age)

  8. VALUES ('Peter', 'Griffin', '35')");

  9. mysql_query("INSERT INTO Persons (FirstName, LastName, Age)

  10. VALUES ('Glenn', 'Quagmire', '33')");

  11. mysql_close($con);

  12. ?>
Copy the code

from the form Insert data into database

Now, create an HTML form that will insert new records into the "Persons" table. HTML form:

  1. Firstname:
  2. Lastname:
  3. Age:
  4. .php". The "insert.php" file connects to the database and retrieves values ​​from the form through the $_POST variable.
  5. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the database table.
Code of insert.php page:

/**

* insert into insert data

* edit: bbs.it-home.org
*/
$con = mysql_connect("localhost","peter","abc123");
    if (!$con)
  1. {
  2. die('Could not connect: ' . mysql_error());
  3. }

  4. mysql_select_db("my_db", $con);

  5. $ sql="INSERT INTO Persons (FirstName, LastName, Age)

  6. VALUES
  7. ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

  8. < ;p>if (!mysql_query($sql,$con))
  9. {
  10. die('Error: ' . mysql_error());
  11. }
  12. echo "1 record added";

  13. mysql_close($con)

  14. ?>

  15. Copy code
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn