开发者

How do I post back to a database?

I am new to PhP and M开发者_运维技巧ySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.

Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.

Any suggestions or links to some examples will be much appreciated. Here is my code.

<form name="form1" method="post" action="">
<div align="center">
<?php 
    include("dbcon.php");
    $query="select * from student order by year, studname";
    $result=@mysql_query($query) or die(mysql_error());
        if(mysql_num_rows($result)>0)
        {
?>

  <label>
  <input type="text" name="txtyear" id="txtyear">
  <input type="submit" name="btnyear" id="btnyear" value="Submit">
  </label>
  <table width="75%" border="1">
      <tr>
        <td align="center" width="20%"><strong>Student Number</strong></td>
        <td align="center" width="27%"><strong>Name</strong></td>
        <td align="center" width="23%"><strong>Course</strong></td>
        <td align="center" width="30%"><strong>Year Level</strong></td>
      </tr>
<?php
    while($row=mysql_fetch_array($result))
    {echo "<tr>";
    echo "<td>".$row['studno']."</td>";
    echo "<td>".$row['studname']."</td>";
    echo "<td>".$row['course']."</td>";
    echo "<td>".$row['year']."</td>";
    echo "</tr>";
    }
?>    

  </table>
<?php
    }
    else
    echo "no records found";
?>
</div>
</form>


You need a WHERE clause. A very basic example might look like this:

$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";

NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.

Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)


You can find more info about Mysql select query syntax on http://dev.mysql.com/doc/refman/5.1/en/select.html.

Also don't use @ for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (@mysql_query($query)) it seems it doesn't make sense anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜