在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");
答案 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 :(得分:0)
您的查询错误,您需要为字符串使用单引号:
"insert into Coach_name (Coach_name,Coach_nationality) VALUES ('".$this->coach."','".$coachNationality."')";
更好的方法是确保字符串中的单个qoutes被转义,如下所示:
... VALUES ('".mysql_real_escape_string($this->coach)."', ..
但你的代码太奇怪了,可能会有更多的错误