Payne's SQL Note #4

Back to Payne's SQL Notebook


Insert A Record

1. Insert A Record into A Table from A Form

Syntax 1:

INSERT INTO table_name
VALUES (value_1, value_2, value_3, ...)

Syntax 2:

INSERT INTO table_name (column_1, column_2, ...)
VALUES (value_1, value_2, ...)

CodeResult
<h1>Insert Data Form</h1>

<form action="insert_data.php" method="post">

<table>
<tr>

// PMID
<td>PMID</td><td><input type="text" name="PMID" size="80" /></td>
</tr>

// Author
<tr>
<td>Author</td><td><input type="text" name="Author" size="80" /></td>
</tr>

// Title
<tr>
<td>Title</td><td><input type="text" name="Title" size="80" /></td>
</tr>

// Journal
<tr>
<td>Journal</td><td><input type="text" name="Journal" size="80" /></td>
</tr>

// Year
<tr>
<td>Year</td><td><input type="text" name="Year" size="80" /></td>
</tr>

// Submit button
<tr>
<td></td><td><input type="submit" /></td>
</tr>
</table>
</form>

</body>
</html>

Insert Data Form

PMID
Author
Title
Journal
Year
<?php

// Create a connection to a MySQL RDBMS.
$con = mysql_connect("localhost", "username", "password");

// If the connection fails, display error message.
if (!$con)
{
    die('Error connecting to MySQL: ' . mysql_error());
}

// Select a database
mysql_select_db("ReferenceDB", $con);

// Insert a record into a table
$sql="INSERT INTO
ReferenceTB (PMID, Author, Title, Journal, Year)
VALUES ('$_POST[PMID]','$_POST[Author]','$_POST[Title]','$_POST[Journal]','$_POST[Year]')";

if (mysql_query($sql, $con)))
{
    echo "Query processed.";
}
else
{
    echo "Error Message: " . mysql_error();
}

// Close the connection.
mysql_close($con);

?>