Rumah >pembangunan bahagian belakang >tutorial php >一段查询代码多处使用可以吗解决办法
一段查询代码多处使用可以吗
<br />$bliang='这是个变量'<br />$sql=SELECT * FROM A表 WHERE cart LIKE '%.$bliang.%'<br />$query=mysql_query($sql);<br />while($row=mysql_fetch_array($query)){<br /> <br /> …………<br />}
<br><?php <br />// <br><font color="#FF8000">------解决方案--------------------</font><br> PHP version 5.3<br>// 数据库操作类 Order by phuai007 <br>// Date 2014/2<br>class my_sql {<br> public $dsn = 'mysql:host=localhost;dbname=lif2';//host为数据库连接地址,dbname为数据库名<br> public $user = 'root'; //数据库连接用户名<br> public $pass = '123456'; //对应的密码<br> public $names = 'SET NAMES UTF8'; //数据库查询编码<br> //查询数据库返回结果<br> public function sql_select($sql) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->query($this->names);<br> return $dbh->query($sql);<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> }<br> //操作单条数据(更新/删除/插入),无返回结果<br> public function sql_one($sql) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->exec($this->names);<br> $dbh->exec($sql);<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> }<br> //操作多条数据(更新/删除),无返回结果<br> public function sql_more($sql, $str) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->exec($this->names);<br> foreach ($str as $arrs) {<br> $dbh->exec($sql . $arrs);<br> }<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> }<br> <br> //参数化查询数据库返回结果(单条)<br> public function cs_sql_select($sql,$str) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);<br> $dbh->query($this->names);<br> $stmt = $dbh->prepare($sql);<br> $stmt->bindValue(":key", $str ,PDO::PARAM_INT);<br> $stmt->execute();<br> return $stmt;<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> } <br> //参数化查询操作多条数据(删除/更新),无返回结果<br> public function cs_sql_more($sql, $str) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);<br> $dbh->exec($this->names);<br> foreach ($str as $arrs) {<br> $stmt = $dbh->prepare($sql);<br> $stmt->bindValue(":key", $arrs,PDO::PARAM_INT);<br> $stmt->execute();<br> }<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> }<br> //参数化查询操作单条数据(删除/更新),无返回结果<br> public function cs_sql_one($sql, $str) {<br> try {<br> $dbh = new PDO($this->dsn, $this->user, $this->pass);<br> $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);<br> $dbh->exec($this->names);<br> $stmt = $dbh->prepare($sql);<br> $stmt->bindValue(":key", $str,PDO::PARAM_INT);<br> $stmt->execute();<br> $dbh = null;<br> }<br> catch(Exception $e) {<br> echo 'error: ' . $e->getMessage();<br> }<br> }<br> <br> <br> ////////<br>}<br>?><div class="clear"> </div>