刚转学php,请大家帮我写段数据库查询类的代码

原创
2016-06-23 14:28:38 590浏览

大家好,本人初转php,想建立一个pdo连接的数据库操作类,但是不知道php的调用方法,请大家指点下。
类文件coon.php内容:

query("SET NAMES UTF8");	$dbh->exec("SET NAMES UTF8");	}	catch(Exception $e)    {    echo 'data error: '.$e->getMessage();    }}//关闭数据库连接public function sql_close(){	$dbh=null;}//查询数据库public function my_query($sql){	$this->sql_open();	//$this->sth = $this->dbh->query($sql); 	//$result = $this->sth->fetchAll();               //return $result;            这里面怎么写才能返回数据?	}}?>


页面调用代码:

my_query('SELECT * FROM user_type order by user_id') as $row){//这里循环输出查询内容}$mysql->sql_close();?>


望详细指点下,实在弄不明白,用asp或asp.net的函数调用方法全不行,我想写一个查询,插入,更新和删除数据的通用函数,外部只要带入sql语句就可以执行的那种。

回复讨论(解决方案)

1楼围观。等大神解答!

$this->dbh = new PDO($dsn, $user, $pass);

你的my_query看上去没错,将注释的那几行打开。先试试看。

终于搞定了,看了网上众多代码,测试失败了无数次,结果是弄出来了,插入,删除,更新的通用类,请大神指点下这样做有没有什么弊端,会不会影响性能等。下一步研究下那个参数化,据说可以防止sql注入。

conn.php内容:

dsn, $this->user,$this->pass);	$dbh->query("SET NAMES UTF8");    return $dbh->query($sql); 	$dbh=null;	}	catch(Exception $e)    {    echo 'error: '.$e->getMessage();    }}//操作单条数据(更新/删除/插入),无返回结果public function sql_one($sql){	try	{	$dbh = new PDO($this->dsn, $this->user,$this->pass);	$dbh->exec("SET NAMES UTF8");    $dbh->exec($sql); 	$dbh=null;	}	catch(Exception $e)    {    echo 'error: '.$e->getMessage();    }}//操作多条数据(更新/删除),无返回结果public function sql_more($sql,$str){	try	{	$dbh = new PDO($this->dsn, $this->user,$this->pass);	$dbh->exec("SET NAMES UTF8");	    foreach($str as $arrs)    {	     $dbh->exec($sql.$arrs);     }	$dbh=null;	}	catch(Exception $e)    {    echo 'error: '.$e->getMessage();    }	}}?>

页面调用函数:
include 'conn.php';$mysql = new my_sql;//操作单挑数据$mysql->sql_one("DELETE FROM `user_type` WHERE `user_id` = ".$_REQUEST['id']."");//读取内容$aa=$mysql->sql_select('SELECT * FROM user_type order by user_id');        foreach ($aa as $row)        {//输出内容echo '';echo ''.$row['user_id'].''.$row['user_name'].''.$row['user_real_name'].''.$row['user_sex'].''.$row['user_tel'].''.$row['user_qq'].''.$row['user_address'].''.$row['user_email'].'删除';echo '';}//操作多条数据$id=$_POST['delAll'];if(isset($id)){$mysql->sql_more("DELETE FROM `user_type` WHERE `user_id` = ",$id);}


上面的操作方法和思路还是沿袭了asp.net开发的习惯,不知道在php开发上实用不,望大神指点一下。

你现在这个不能防注入,防注入需要用PDO::prepare

prepare('SELECT name, colour, calories    FROM fruit    WHERE calories execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>

你现在这个不能防注入,防注入需要用PDO::prepare

prepare('SELECT name, colour, calories    FROM fruit    WHERE calories execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>

你说的这个方法我已经会弄了,参数化查询
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。