Heim  >  Artikel  >  Backend-Entwicklung  >  求问小弟我自己写的这个DB类,错哪了,插不进数据

求问小弟我自己写的这个DB类,错哪了,插不进数据

WBOY
WBOYOriginal
2016-06-13 12:48:49748Durchsuche

求问我自己写的这个DB类,哪里错了,插不进数据

<?php<br />
	class DB{<br />
		private $hostname;<br />
		private $username;<br />
		private $password;<br />
		private $select_db;<br />
		private $con;<br />
		private $Error;<br />
		<br />
		public function __construct($hostname,$username,$password,$select_db){<br />
			if(!empty($hostname)&&!empty($username)&&!empty($select_db))//检查参数是否为空,否则不赋值<br />
			{<br />
				$this->hostname = $hostname;<br />
				$this->username = $username;<br />
				$this->password = $password;<br />
				$this->select_db = $select_db;<br />
				$this->con = mysql_connect($this->hostname,$this->username,$this->password);<br />
				if(!$this->con){<br />
					$this->Error = die('Could Not Connect:'.mysql_error);<br />
				}<br />
				else{<br />
					mysql_select_db($this->select_db,$this->con);<br />
				}<br />
			}<br />
		}<br />
		public function __destruct(){//退出时结束连接<br />
			mysql_close($this->con);<br />
		}<br />
		public function insert($table,$body){//插入table中的一个数组<br />
			$line1 = implode(',',$body);<br />
			$line2 = implode(',',array_keys($body));<br />
			echo $sql = "INSERT INTO $table ($line2) VALUES ($line1)";<br />
			$result = mysql_query($sql,$this->con);<br />
			if(!$result){<br />
				echo $this->Error;<br />
				echo '111';<br />
			}<br />
			<br />
		}<br />
		public function update($table,$body){<br />
		<br />
		}<br />
		public function read($table,$keyword){<br />
			<br />
		}<br />
		public function delete($table,$keyword){<br />
		<br />
		}<br />
		public function getLastError(){//返回最后一条错误信息<br />
			return $this->Error;<br />
		}<br />
	}<br />
?>

主页调用的是
<?php<br />
require('DB.class.php');<br />
	$DB = new DB('localhost','root','','dbtest');<br />
	$line1 = array(<br />
			'aa'=>'`aa`',<br />
			'bb'=>'`dd`'<br />
	);<br />
	$DB->insert('1234',$line1);<br />
?>

echo $sql语句是INSERT INTO 1234 (aa,bb) VALUES (`aa`,`dd`)


------解决方案--------------------
require('DB.class.php');
    $DB = new DB('localhost','root','','dbtest');
    $line1 = array(
            'aa'=> "'aa'",
            'bb'=> "'dd'"
    );
    $DB->insert('1234',$line1);

------解决方案--------------------
你的$line1数组写反了。
而且insert 语句还有一种格式:insert into tb_member set username = "test", type = 1, lastlogindt = now()。跟update样式差不多。
你也可以看看人家写的数据库类,我感觉挺好的:http://www.cnblogs.com/hooray/archive/2012/07/21/2603017.html
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn