-1

在 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");
4

2 回答 2

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. mysql_query的第二个参数应该是连接
  4. 开始使用 PDO 或 mysqli 而不是 mysql,因为它将在未来的版本中从 PHP 中删除,并且已经被认为是过时的实践。
于 2013-02-27T14:22:06.430 回答
0

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

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

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

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

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

于 2013-02-27T14:11:19.937 回答