HTML和PHP数据库连接

时间:2014-03-23 07:51:55

标签: php mysql connectivity

我正在使用此代码。在数据库“dbname”中名为“tablename”的表中插入name和rollno。

db.php中

<html>
    <body>
        <form name="db" action="db.php" method=post>
            Enter name <input type=text name="nam"/><br><br>
            Enter RollNo. <input type=text name="rno"/><br><br>
            <input type=submit value="Click me"/>
        </form>

<?php
$nam = $_POST['nam'];
$rno = $_POST['rno'];
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('dbname') or die(mysql_error());
$sql="insert into tablename values('$nam','$rno')";
 mysql_query($sql);
?>
</body>
</html>

显示错误,即 注意:未定义的索引:第10行的C:\ wamp \ www \ DB Connectivity \ db.php中的nam
注意:未定义的索引:第11行的C:\ wamp \ www \ DB Connectivity \ db.php中的rno

Plz给出解决方案,如何在同一页面中使用html和php而不会出现此错误。

2 个答案:

答案 0 :(得分:0)

您没有检查是否提交了表单,因此只需为您的提交元素提供名称&amp;必须使用isset

进行检查
    <input type=submit name="submit" value="Click me"/>
    </form>

<?php
if(isset($_POST['submit'])){
     $nam = isset($_POST['nam']) ? $_POST['nam'] : '';
     $rno = isset($_POST['rno']) ? $_POST['rno'] : '';
     //And rest of your php operation you need to perform after submit.
?>

警告: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 1 :(得分:0)

试试这个

    <?php 
    $connection = mysql_connect("localhost","root","") or die(mysql_error());
    $db = mysql_select_db("dbname") or die(mysql_error());
    $nam = $_POST['nam'];
    $rno = $_POST['rno'];
    if(!empty($_POST['submit'])){
       $insert_qry = mysql_query("INSERT INTO `table_name` (`nam`, `rno`) VALUES ('".$nam."','".$rno."') ") or die(mysql_error());
    }
   ?>
<html>
<body>
   <form name="db" action="" method="post">
      Enter name
      <input type="text" name="nam"/>
      <br>
      <br>
      Enter RollNo.
      <input type="text" name="rno"/>
      <br>
      <br>  
      <input type="submit" name="submit" value="Click me"/>
  </form>
</body>
</html>