I’m trying to call a function from a form within the same .php file, but when the Submit button is hit, the table doesn’t get generated.
Here’s the code:
<p>
<?php
function selectQuery()
{
$con = mysql_connect("localhost","readonly","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mediadb", $con);
$result = mysql_query("SELECT title, director FROM movies WHERE year = '$_POST[year_txt]'");
echo "<table border='1' background='lightgray'>
<tr>
<th>Title</th>
<th>Director</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['director'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
}
?>
</p>
<p>
<!-- start of entry form -->
<form action="index.php?action=selectQuery" method="post">
Year: <input type="text" name="year_txt" />
<input type="submit"/>
</form>
<!-- end of entry form -->
</p>
Any idea why this isn’t working?
If you’re expecting an integer as a year, get it from the POST superglobal as
And add a parameter to your select function to take the year, then execute how like SanHolo suggested.
BTW, note I cast the variable to an integer (the (int) part) in the example I provided. The code as you have it is a huge security hole. You need to look up data santization, SQL injection, and possibly parameterized prepared statements (check out PDO).
Where you put in $_POST[‘year_txt’], someone could put ANYTHING straight into your SQL statement… Like, “90;delete from movies where 1;”. Check out the SQL statement that would create!
Do not ever print out user supplied input and CERTAINLY don’t put it into an SQL command without first checking it for sanity and sanitizing it. If it’s a number, cast to int. If you’re receiving a string, use preg_replace to filter out any odd characters. You can also use certain PHP filter_var functions – http://php.net/manual/en/function.filter-var.php