doudao1282
2012-09-20 04:03
浏览 45
已采纳

如何使用oops php5概念将数据插入mysql数据库?

I am new for PHP5 OOP concept. Please give some example source code for "How to insert data using oops concept?".I want to use pure php5 concept for this even in the connection.php page also. I want to improve my knowledge. please any one help me....

I know below the basic concept

insert_db.php

                $sql="INSERT INTO Persons (FirstName, LastName, Age)
            VALUES
            ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

            if (!mysql_query($sql,$con))
              {
              die('Error: ' . mysql_error());
              }
            echo "1 record added";

            mysql_close($con)

connectio.php

          <?php
            // connect database  code
             $dbhost ='localhost';
            $dbuser = 'tomking';
            $dbpass = 'dsfds';
            $dbname = 'mydb';
            //connectivity of database
            $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error Connecting to mysql');
            mysql_select_db($dbname);
          ?>

图片转代码服务由CSDN问答提供 功能建议

我是PHP5 OOP概念的新手。 请给出一些“如何使用oops概念插入数据”的示例源代码 ?“。我想在连接.php页面中使用纯php5概念。 我想提高我的知识。 请任何人帮助我....

我知道以下基本概念

insert_db.php

  $ sql =“INSERT INTO Persons(FirstName,LastName,Age)
 VALUES 
('$ _POST [firstname]','$ _ POST [lastname]','$ _ POST  [age]')“; 
 
 if(!mysql_query($ sql,$ con))
 {
 die('Error:'。mysql_error()); 
} 
 echo”添加了1条记录 “; 
 
 mysql_close($ con)
   
 
 

connectio.php
 &lt;?php \  n //连接数据库代码
 $ dbhost ='localhost'; 
 $ dbuser ='tomking'; 
 $ dbpass ='dsfds'; 
 $ dbname ='mydb'; 
 //数据库连接\  n $ conn = mysql_connect($ dbhost,$ dbuser,$ dbpass)或die('错误连接到mysql'); 
 mysql_select_db($ dbname); 
?&gt; 
   \  n 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douke6424 2012-09-20 04:18
    已采纳

    Use Mysqli or PDO for using sql queries instead of directly pass variables to query.

    This will cause sql injection when you directly pass variable to query

    If you want to pass variable to sql query , you have to use filters for this

    filtering-escaping-post-data-from-injection-attacks

    PDO Documentation

    MySQLi Documentation

    And this is all pure PHP5 concept.

    点赞 打赏 评论
  • duanpao9781 2012-09-20 04:21
    $mysqli = new mysqli($hostname, $username, $password, $database_name);
    
    if($mysqli->error)
        die($mysqli->error);
    
    $mysqli->query("SET NAMES 'UTF8'");
    
    $query = "INSERT INTO my_table VALUES ('value_1', 'value_2')";
    $mysqli->query($query);
    if(!$mysql->error)
       echo 'do something';
    
    $query = "SELECT * FROM my_table";
    $sql = $mysqli->query($query);
    if($sql->num_rows > 0) {
        while($row = $sql->fetch_assoc()) {
            echo $row['field_1'];
        }
    }
    $sql->close();
    
    点赞 打赏 评论

相关推荐 更多相似问题