使用面向对象编程将值插入数据库

时间:2012-06-14 06:12:29

标签: php

  

可能重复:
  How to successfully rewrite old mysql-php code with deprecated mysql_* functions?

我无法将值插入数据库中。但是,我也没有收到任何错误消息。

<html>
<body>
<form action="database.php" method="post">
Name : <input type ="text" name = "name"/>
Number  :<input type ="text" name = "number"/>
<input type ="submit" value = "submit"/>
</form>
</body>
</html>

database.php中

<?php
class Database
{
    var $host;
    var $user;
    var $pass;
    var $data;
    var $con;
    var $table;
    var $db;

    public function controls()
    {
        $this->host="localhost";
        $this->user="cgiadmin";
        $this->pass="cgi";
        $this->data="j2";
    }

    public function connection()
    {
        $this->con="mysql_connect($this->host,$this->user,$this->pass)";
    }
    public function tablename()
    {
        $this->table="Insert into employee(name,number) values('$_POST[name]','$_POST[number]')";
    }
    public function databaseconnection()
    {
        $this->db="mysql_select_db($this->data,$this->con)";
    }

}
$name=new Database;
$name->connection();
if(!($name->con))
{
    echo "'Error: ' . mysql_error()";
}

$name->databaseconnection();
$name->tablename();

echo "thanks for taking the survey";

?>

2 个答案:

答案 0 :(得分:2)

试试这个......

修改tablename()函数

public function tablename($nam,$num)
    {
        $this->table=mysql_query("INSERT INTO employee(name,number) VALUES ('$nam','$num')");
    }

获取值并调用tablename()函数

$name=new Database;
$name->connection();
if(!($name->con))
{
    echo "'Error: ' . mysql_error()";
}

$name->databaseconnection();

$nam=$_POST[name];
$num=$_POST[number];
$name->tablename($nam,$num);

echo "thanks for taking the survey";

答案 1 :(得分:-3)

你需要一些魔力:)阅读php中的quotes

<?php
class Database
{
    var $host;
    var $user;
    var $pass;
    var $data;
    var $con;
    var $table;
    var $db;

    public function controls()
    {
        $this->host="localhost";
        $this->user="cgiadmin";
        $this->pass="cgi";
        $this->data="j2";
    }

    public function connection()
    {
        $this->con = mysql_connect($this->host,$this->user,$this->pass);
    }
    public function tablename()
    {
        $this->table=mysql_query("INSERT INTO employee(name,number) VALUES ('".$_POST[name]."','".$_POST[number]."')");
    }
    public function databaseconnection()
    {
        $this->db=mysql_select_db($this->data,$this->con);
    }

}
$name=new Database();
$name->controls();
$name->connection();
if(!($name->con))
{
    echo 'Error: ' . mysql_error();
}

$name->databaseconnection();
$name->tablename();

echo "thanks for taking the survey";

?>