启动对象后,PHP OOP连接mysql不起作用

时间:2013-02-27 14:05:29

标签: php mysql

在oop php中,我创建了构造函数mysql连接(我知道它会被弃用,你会使用PDO等等),但我遇到了问题。连接完成,一切正常。但是插入不了不知道为什么,代码运行到最后。似乎对象不接受连接,但它不可能。 PHP 5.4.3我使用。代码如下:

Table (Coach):
Coach_id INT (AutoIncrement)
Coach_name char(30)
Coach_nationality char(30)


class League 
{
    public $con;

    public function MySQLCon()
    {
    $this->con = mysql_connect("localhost","root","") or mysql_error($this->con);
    mysql_select_db("basket",$this->con) or mysql_error($this->con);
    return $this->con;
    }

    public $coach,$coachNationality;

    public function NewCoach($coach,$coachNationality)
    {

        $this->coach = $coach;
        $this->coachNationality = $coachNationality;

        $Query = "insert into Coach_name (Coach_name,Coach_nationality) VALUES ('".$this->coach."','".$this->coachNationality."')";

        //this query doesn't do anything but prints yes
        mysql_query($Query,$this->con) or mysql_error($this->con);
        echo "yes";

    }
}

//no data about mike Brown in database, database engine InnoDB
$LG = new League;
$LG->MySQLCon();
$LG->NewCoach("Mike Brown","USA");

2 个答案:

答案 0 :(得分:1)

首先使用错误消息开始:

class League 
{
    var $con;

    public function __construct()
    {
    $this->con = mysql_connect("localhost","root","") or die("No connection: " . mysql_error());
    mysql_select_db("basket",$this->con) or die("Database could not be selected: " . mysql_error($this->con));
    }

    public $coach,$coachNationality;

    public function NewCoach($coach,$coachNationality)
    {

        $this->coach = $coach;
        $this->coachNationality = $coachNationality;

        $Query = "insert into Coach_name (Coach_name,Coach_nationality) VALUES ('".$this->coach."','".$this->coachNationality."')";

        //this query doesn't do anything but prints yes
        mysql_query($Query,$this->con) or die(mysql_error($this->con));
        return true;    
    }
}

//no data about mike Brown in database, database engine InnoDB
$LG = new League;
if( $LG->NewCoach("Mike Brown","USA") ) echo "inserted, method NewCoach returned true";

编辑完代码后;

  1. mysql_error将接收的唯一参数是连接,而不是字符串。
  2. 插入和选择中的
  3. 字符串需要用引号''或“”包围。
  4. mysql_query的第二个参数应该是连接
  5. 开始使用PDO或mysqli而不是mysql,因为它将在未来的版本中从PHP中删除,并且已经被认为是回到练习和过时。

答案 1 :(得分:0)

您的查询错误,您需要为字符串使用单引号:

"insert into Coach_name (Coach_name,Coach_nationality) VALUES ('".$this->coach."','".$coachNationality."')";

更好的方法是确保字符串中的单个qoutes被转义,如下所示:

... VALUES ('".mysql_real_escape_string($this->coach)."', ..

但你的代码太奇怪了,可能会有更多的错误