Match a field from a form's contents with a table in a database (MySQL)
I have set up a form on my site. And I'm wondering, how can I match what people enter in a field in that form with something in another table. The form submits to one table, and I want to check if what's submitted with the form is in another table.
In this case, I have a field named开发者_StackOverflow社区 "Title", and I want to check if what's been entered from that form under "Title" is in another table.
Thanks for your help.
Here is a rough outline:
Step 1: User fills out title and hits submit
Step 2: Page(code) that will inserts the user input runs the following
if (ctype_alnum($_POST['title']) { // Make sure the title is alphanumeric, not required but useful
$title = mysql_real_escape_string($_POST['title']); // This cleans the input if you don't use ctype_alnum
$sql = "SELECT * FROM table2 WHERE Title = $title"; // Query to find out if it exists in table 2
$result = mysql_query($sql); // Runs the query
if (mysql_num_rows($result) > 0) // Check to see if a row was found
$titleInTable2 = true; // Set a variable to true if a row was found
}
So the only issue with the above code is that it only looks for exact matches. If you want a partial match, look into using LIKE %...%
or MATCH
Like: http://dev.mysql.com/doc/refman/4.1/en/string-comparison-functions.html
Match: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
精彩评论