刚转学php,请大家帮我写段数据库查询类的代码
大家好,本人初转php,想建立一个pdo连接的数据库操作类,但是不知道php的调用方法,请大家指点下。
类文件coon.php内容:
<?phpclass my_sql{public $dbh;public $sth;//连接数据库public function sql_open(){ $host='localhost'; //数据库主机名 $dbName='lif2'; //使用的数据库 $user='root'; //数据库连接用户名 $pass='123456'; //对应的密码 $dsn='mysql:host='.$host.';dbname='.$dbName; try { $dbh = new PDO($dsn, $user, $pass); $dbh->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; 这里面怎么写才能返回数据? }}?>
页面调用代码:
<body><?phpinclude 'conn.php';$mysql = new my_sql;foreach ($mysql->my_query('SELECT * FROM user_type order by user_id') as $row){//这里循环输出查询内容}$mysql->sql_close();?></body>
望详细指点下,实在弄不明白,用asp或asp.net的函数调用方法全不行,我想写一个查询,插入,更新和删除数据的通用函数,外部只要带入sql语句就可以执行的那种。
回复讨论(解决方案)
1楼围观。等大神解答!
$this->dbh = new PDO($dsn, $user, $pass);
你的my_query看上去没错,将注释的那几行打开。先试试看。
终于搞定了,看了网上众多代码,测试失败了无数次,结果是弄出来了,插入,删除,更新的通用类,请大神指点下这样做有没有什么弊端,会不会影响性能等。下一步研究下那个参数化,据说可以防止sql注入。
conn.php内容:
<?php//数据库操作类class my_sql{public $user='root'; //数据库连接用户名public $pass='123456'; //对应的密码public $dsn='mysql:host=localhost;dbname=lif2';//查询数据库返回结果public function sql_select($sql){ try { $dbh = new PDO($this->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 '<tr>';echo '<td>'.$row['user_id'].'</td><td>'.$row['user_name'].'</td><td>'.$row['user_real_name'].'</td><td>'.$row['user_sex'].'</td><td>'.$row['user_tel'].'</td><td>'.$row['user_qq'].'</td><td>'.$row['user_address'].'</td><td>'.$row['user_email'].'</td><td><a href="?action=del&id='.$row['user_id'].'" title="删除">删除</a></td><td><input name="delAll[]" class="c" type="checkbox" value="'.$row['user_id'].'" /></td>';echo '</tr>';}//操作多条数据$id=$_POST['delAll'];if(isset($id)){$mysql->sql_more("DELETE FROM `user_type` WHERE `user_id` = ",$id);}
上面的操作方法和思路还是沿袭了asp.net开发的习惯,不知道在php开发上实用不,望大神指点一下。
你现在这个不能防注入,防注入需要用PDO::prepare
<?php/* Execute a prepared statement by passing an array of values */$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?');$sth->execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>
你现在这个不能防注入,防注入需要用PDO::prepare
<?php/* Execute a prepared statement by passing an array of values */$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?');$sth->execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>
你说的这个方法我已经会弄了,参数化查询

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
