通过php在mysql中插入数据

时间:2012-09-14 14:28:52

标签: php mysql

在我的代码中只是通过php将一些数据插入到mysql数据库中。插入所有数据,但不插入两列的数据。 我的代码::

regi.php
  //表单设计

 <html>
    <form action="regi_pp.php"  method="post">
      Student Name <input name="st_name" type="text" id="st_name">
       Father's Name  <input name="f_name" type="text" id="f_name">
      Mother's Name <input name="m_name" type="text" id="m_name">
      Faculty  <input name="faculty" type="text" id="faculty">
      Department <input name="department" type="text" id="department">
      Session <input name="session" type="text" id="session">  
     Dormitory  <input name="dormitory" type="text" id="dormitory">  
    Registration No <input name="regi_no" type="text" id="regi_no"> 
     Email  <input name="email" type="text" id="email"> 
     pass:<input name="pass" type="password" id="pass">  
     <input type="submit" name="Submit" value="Submit">
     </form>
 </html>

提交::

之后
 <?php 
    $st_name=$_POST["st_name"];   // name
    $st_father=$_POST["f_name"];   // father name
    $st_mother=$_POST["m_name"];   // Mather name
    $faculty=$_POST["faculty"];     // faculty name
    $dept=$_POST["department"];     // department name
    $session=$_POST["session"];     // session  
    $dormitory=$_POST["dormitory"];  // dormitory 
    $regi_no=$_POST["regi_no"];     //regi number
    $email=$_POST["email"];         //  email
    $pass=$_POST["pass"];          // password

   $con = mysql_connect("localhost","root","");   // mysql connection

    mysql_select_db("ppp", $con);    // database connection

    // here all value insert but '$regi_no', '$email' are not inserted and '$pass' value only insert if $pass value is number 
    mysql_query("INSERT INTO regf            VALUES('$st_name','$st_father','$st_mother','$faculty','$dept','$session','$dormitory','$regi_no','$email','$pass')") or die(mysql_error());
     mysql_close($con);
 ?>

1 个答案:

答案 0 :(得分:1)

如果在宿舍我输入Saint Philip Dormitory'); DROP TABLE regfs;--怎么办?您认为会发生什么?

您的代码容易出现 SQL Injection 。请改用 PDO MYSQLI 扩展程序。

使用PDO扩展的示例:

<?php

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
    $stmt->bindParam(1, $name);
    $stmt->bindParam(2, $value);

    // insert one row
    $name = 'one';
    $value = 1;
    $stmt->execute();

?>

这将允许您插入带单引号的记录。