刚转学php,请大家帮我写段数据库查询类的代码
大家好,本人初转php,想建立一个pdo连接的数据库操作类,但是不知道php的调用方法,请大家指点下。
类文件coon.php内容:
<br /><?php<br />class my_sql<br />{<br />public $dbh;<br />public $sth;<br />//连接数据库<br />public function sql_open()<br />{<br /> $host='localhost'; //数据库主机名<br /> $dbName='lif2'; //使用的数据库<br /> $user='root'; //数据库连接用户名<br /> $pass='123456'; //对应的密码<br /> $dsn='mysql:host='.$host.';dbname='.$dbName;<br /> try<br /> {<br /> $dbh = new PDO($dsn, $user, $pass);<br /> $dbh->query("SET NAMES UTF8");<br /> $dbh->exec("SET NAMES UTF8");<br /> }<br /> catch(Exception $e)<br /> {<br /> echo 'data error: '.$e->getMessage();<br /> }<br />}<br />//关闭数据库连接<br />public function sql_close()<br />{<br /> $dbh=null;<br />}<br /><br />//查询数据库<br />public function my_query($sql)<br />{<br /> $this->sql_open();<br /> //$this->sth = $this->dbh->query($sql); <br /> //$result = $this->sth->fetchAll(); <br /> //return $result; <br /> 这里面怎么写才能返回数据?<br /> }<br />}<br />?><br />
<br /><body><br /><?php<br />include 'conn.php';<br />$mysql = new my_sql;<br /><br />foreach ($mysql->my_query('SELECT * FROM user_type order by user_id') as $row)<br />{<br />//这里循环输出查询内容<br />}<br /><br />$mysql->sql_close();<br />?><br /></body><br />
<br /><?php<br />/* Execute a prepared statement by passing an array of values */<br />$sth = $dbh->prepare('SELECT name, colour, calories<br /> FROM fruit<br /> WHERE calories < ? AND colour = ?');<br />$sth->execute(array(150, 'red'));<br />$red = $sth->fetchAll();<br />$sth->execute(array(175, 'yellow'));<br />$yellow = $sth->fetchAll();<br />?><br />