如果您对解决PHPPDO读取MSSQL数据乱码问题感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于解决PHPPDO读取MSSQL数据乱码问题的详细内容,我们还将为您解答php
如果您对解决 PHP PDO 读取 MSSQL 数据乱码问题感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于解决 PHP PDO 读取 MSSQL 数据乱码问题的详细内容,我们还将为您解答php读取mysql的相关问题,并且为您提供关于1、PDO:PDO 简介、5.3 版本 php 与 5.5 公用的 pdo 技巧、Codeigniter PDO 错误连接注意:尝试获取非对象的属性文件名 pdo/pdo_driver.php、CRUD with PHP MVC, PDO, JSON and Twitter Bootstrap的有价值信息。
本文目录一览:- 解决 PHP PDO 读取 MSSQL 数据乱码问题(php读取mysql)
- 1、PDO:PDO 简介
- 5.3 版本 php 与 5.5 公用的 pdo 技巧
- Codeigniter PDO 错误连接注意:尝试获取非对象的属性文件名 pdo/pdo_driver.php
- CRUD with PHP MVC, PDO, JSON and Twitter Bootstrap
解决 PHP PDO 读取 MSSQL 数据乱码问题(php读取mysql)
因为工作需要从一个 MS SQL Server 数据库中读取数据并进行处理。由于代码库是 PHP 为主,所以需要通过 PHP 的 PDO 方式链接 SQL 数据库并读取数据。ODBC 方式很容易实现,链接代码如下:
$str = odbc:Server=localhost;Database=db;
$conn = new PDO($str, $userID, $pwd);
确保 php_pdo.dll, php_pdo_odbc.dll 扩展加载就可以了。然后数据表里的特殊字符乱码问题无法解决。尝试启用 ODBC_ATTR_ASSUME_UTF8=true, 乱码字符倒是可以正常显示了,但是大量的原本正常的字段出现乱码。一顿搜索后,有人说需要用 sqlsrv 驱动,于是修改代码如下:
$str = sqlsrv:Server=localhost;Database=db;
$conn = new PDO($str, $userID, $pwd);
报错
PHP Fatal error: Uncaught exception ''PDOException'' with message ''SQLSTATE[IMSSP]: This extension requires the Microsoft SQL Server 2012 Native Client ODBC Driver to communicate with SQL Server.
在 https://www.php.net/manual/zh/ref.pdo-sqlsrv.php 发现解决方案,安装相应的 ODBC 驱动就好啦。
1、PDO:PDO 简介
5.3 版本 php 与 5.5 公用的 pdo 技巧
$data_conn = array();
$data_conn[''host''] = ''host'';
$data_conn[''user''] = ''user'';
$data_conn[''passwd''] = ''pass'';
// 连接数据库
function conn_mysql($conn_array){
$dsn = ''mysql:host='' . $conn_array[''host''] . '';dbname='';
$option = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
if (version_compare(PHP_VERSION, ''5.3.6'', ''<'')) {
if (defined(''PDO::MYSQL_ATTR_INIT_COMMAND'')) {
$option[PDO::MYSQL_ATTR_INIT_COMMAND] = ''SET NAMES utf8'';
}
} else {
$dsn .= '';charset=utf8'';
}
$conn = [@new](https://my.oschina.net/u/121421) PDO($dsn, $conn_array[''user''], $conn_array[''passwd''], $option);
if (version_compare(PHP_VERSION, ''5.3.6'', ''<'') && !defined(''PDO::MYSQL_ATTR_INIT_COMMAND'')) {
$sql = ''SET NAMES utf8'';
$conn->exec($dw_sql);
}
return $conn;
}
$data_db = conn_mysql($data_conn);
Codeigniter PDO 错误连接注意:尝试获取非对象的属性文件名 pdo/pdo_driver.php
如何解决Codeigniter PDO 错误连接注意:尝试获取非对象的属性文件名 pdo/pdo_driver.php
我正在尝试在 pdo pgsql(第二个数据库)中插入数据,但我很清楚这个注意:试图获取非对象的属性。文件名:pdo/pdo_driver.PHP。
这是我与数据库的连接:
with open(file_path) as csv_file:
data_source = csv.reader(csv_file,delimiter='','')
with open(output_path + ''results.csv'',''w'',newline='''') as results_file:
data_sink = csv.writer(results_file) #This is the important line
for line in data_source:
data_sink.writerow(line)
在我的模型中,我有这个功能(这里只是重要的东西,不完整):
$active_group = ''default'';
$query_builder = TRUE;
$db[''pdo_email''] = array(
''hostname'' => ''pgsql:host=00.00.00.00;dbname=db_name;port=5432'',''username'' => ''user'',''password'' => ''password'',''database'' => ''db_name'',''dbdriver'' => ''pdo'',''dbprefix'' => '''',''pconnect'' => FALSE,''db_debug'' => (ENVIRONMENT !== ''production''),''cache_on'' => FALSE,''cachedir'' => '''',''char_set'' => ''utf8'',''dbcollat'' => ''utf8_general_ci'',''swap_pre'' => '''',''encrypt'' => FALSE,''compress'' => FALSE,''stricton'' => FALSE,''failover'' => array(),''save_queries'' => TRUE
);
解决方法
我使用 POSTGRES 的数据库连接设置:
$active_group = ''default'';
$query_builder = TRUE;
$db[''default''] = array(
''dsn'' => '''',''hostname'' => ''pgsql:host=localhost;dbname=Absences_DB'',''username'' => ''postgres'',''password'' => ''marc'',''database'' => ''Absences_DB'',''dbdriver'' => ''pdo'',''dbprefix'' => '''',''pconnect'' => FALSE,''db_debug'' => (ENVIRONMENT !== ''production''),''cache_on'' => FALSE,''cachedir'' => '''',''char_set'' => ''utf8'',''dbcollat'' => ''utf8_general_ci'',''swap_pre'' => '''',''encrypt'' => FALSE,''compress'' => FALSE,''stricton'' => FALSE,''failover'' => array(),''save_queries'' => TRUE
);
您应该验证是否在 php.ini 文件中启用了 pdo 驱动程序
CRUD with PHP MVC, PDO, JSON and Twitter Bootstrap
We will create a CRUD application by using MVC design pattern, PDO extension, Jquery and Twitter Bootstrap.
We will use JSON as data-interchange format for HTTP request and response.
To learn about::
MVC Design Pattern -> link1, link2
PDO -> link1, link2
JSON -> link
Twitter Bootstrap -> link
Before start coding you can take a look on the demo:: Demo
First of all we create a table and populate it, use below script::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
CREATETABLEIFNOTEXISTS `users` (
`id`int(11)NOTNULLAUTO_INCREMENT,
`name`varchar(50)CHARACTERSETlatin1NOTNULL,
`email`varchar(150)CHARACTERSETlatin1NOTNULL,
`mobile`varchar(20)CHARACTERSETlatin1NOTNULL,
`address`varchar(255)CHARACTERSETlatin1NOTNULL,
PRIMARYKEY(`id`)
) ENGINE=MyISAM DEFAULTCHARSET=utf8 AUTO_INCREMENT=56 ;
INSERTINTO`users` (`id`, `name`, `email`, `mobile`, `address`)VALUES
(1,''Al-Amin Khan'',''al@min.com'',''6546464'',''Dhaka,Bangladesh''),
(2,''Sahed Bhuiyan'',''s@hed.com'',''987979'',''Khulna, Bangladesh''),
(3,''Mamun'',''m@mun.com'',''1234'',''Dhaka, Bangladesh''),
(9,''foysal'',''foysal@yahoo.com'',''1234556'',''Dhaka, Bangladesh.'');
|
Directory Structure::
We have only two parent directory “models” and “ui”. So create these two directory in your app location.
Download Twitter Bootstrap from “Bootstrap“. and put it just under “ui” directory.
Now we will create all our views related files. So create “index.php” in app directory and put below code::
1
2
3
4
5
|
<?phpinclude("ui/header.htm"); ?>
<?phpinclude("ui/nav.htm"); ?>
<div id="content"></div>
<?phpinclude("ui/deleteconfirmmodal.htm"); ?>
<?phpinclude("ui/footer.htm"); ?>
|
In this “index.php” file we included all our static content as files. We will load our dynamic content in “content” div.
Next in “ui” directory create four new files “header.htm”, “footer.htm”, “nav.htm” and “deleteconfirmmodal.htm” which we already included in “index.php”. Now put content of each file from below::
header.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!DOCTYPEhtml>
<htmlxmlns="
http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/>
<title>JSON CRUD</title>
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<linkhref="ui/css/bootstrap.min.css"rel="stylesheet"media="screen">
<linkhref="ui/css/crud.css"rel="stylesheet"media="screen">
</head>
<body>
<div>
<div>
<h1>JSON CRUD</h1>
</div>
|
footer.htm
1
2
3
4
5
6
7
|
</div>
<scriptsrc="
http://code.jquery.com/jquery.js"></script>
<scriptsrc="ui/js/bootstrap.min.js"></script>
<scriptsrc="ui/js/custom.js"></script>
</body>
</html>
|
You can see in footer we are including “jquery” from online, if you dont have internet at your working machine then collect the latest “jquery” and load it from your local in this footer section.
nav.htm
1
2
3
4
5
6
7
8
9
10
11
12
|
<div>
<div>
<ul>
<li><ahref="javascript:void(0);"id="user_list"><i></i> Read</a></li>
<li><ahref="javascript:void(0);"id="create_user_form"><i></i> Create</a></li>
</ul>
</div>
</div>
<divid="indicator">
<imgsrc="ui/img/indicator.gif"/>
</div>
|
deleteconfirmmodal.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<divid="delete_confirm_modal"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
<div>
<h3id="myModalLabel">Delete User</h3>
</div>
<div>
<p>Are you sure to delete this user?</p>
</div>
<div>
<inputtype="hidden"id="user_id"value=""/>
<buttondata-dismiss="modal"aria-hidden="true">No</button>
<button>Yes</button>
</div>
</div>
|
You will need one css file and one image, you will get it “ui -> css -> crud.css” and “ui -> img -> indicator.gif” from downloaded package of this example, and put this files in proper directory.
Create a controller “Controller.php” in app location. and put below code in it::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php
function__autoload($className){
include_once(''models/$className.php'');
}
$users=newUser(''your_host'',''your_user'',''your_password'',''your_database'');
if(!isset($_POST''action''])) {
printjson_encode(0);
return;
}
switch($_POST[''action'']) {
}
exit();
|
Create “User.php” in “models” directory, this is our user model class. put below code in it::
1
2
3
4
5
6
7
8
9
10
|
<?php
classUser {
private$dbh;
publicfunction__construct($host,$user,$pass,$db) {
$this->dbh =newPDO("mysql:host=".$host.";dbname=".$db,$user,$pass);
}
}
|
For our custom javascript create a “custom.js” file in “ui -> js” directory. and put below code::
1
2
|
$(function() {
});
|
At this point if you access your this application you will get a page like below::
Now we will functionality one by one.
First of all we will add “Read” functionality. On “Read” button click we will display all user list from database in our “content” div by Ajax call.
So add a line in “custom.js” file’s “$(function()” block like below::
1
2
3
|
$(function() {
$(document).on("click","a#user_list",function(){ getUserList(this); });
});
|
Here we are adding a click listener on “user_list” link click.
After that block add below functions “getUserList” and “renderUserList”::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
functiongetUserList(element) {
$(''#indicator'').show();
$.post(''controller.php'',
{
action:''get_users''
},
function(data, textStatus) {
renderUserList(data);
$(''#indicator'').hide();
},
"json"
);
}
functionrenderUserList(jsonData) {
vartable =''<table width="600" cellpadding="5"><thead><tr><th scope="col">Name</th><th scope="col">Email</th><th scope="col">Mobile</th><th scope="col">Address</th><th scope="col"></th></tr></thead><tbody>'';
$.each( jsonData,function( index, user){
table +=''<tr>'';
table +=''<tdfield="name" user_id="''+user.id+''">''+user.name+''</td>'';
table +=''<tdfield="email" user_id="''+user.id+''">''+user.email+''</td>'';
table +=''<tdfield="mobile" user_id="''+user.id+''">''+user.mobile+''</td>'';
table +=''<tdfield="address" user_id="''+user.id+''">''+user.address+''</td>'';
table +=''<td><a href="javascript:void(0);" user_id="''+user.id+''"><i></i></a></td>'';
table +=''</tr>'';
});
table +=''</tbody></table>'';
$(''div#content'').html(table);
}
|
By above function “getUserList” we are sending a “get_users” POST request to collect all users as JSON data and with these JSON data function “renderUserList” is rendering user list in a table.
Open “Controller.php” and add below “case” block in “switch” ::
1
2
3
|
case''get_users'':
print$users->getUsers();
break;
|
Now we have to add “getUsers” mathod to “User” model class. so open “User.php” file and add this below method::
1
2
3
4
5
|
publicfunctiongetUsers(){
$sth=$this->dbh->prepare("SELECT * FROM users");
$sth->execute();
returnjson_encode($sth->fetchAll());
}
|
Now if you click on “Read” button you can see a nice table with all users like below without whole page load::
To create functionality, open “custom.js” and add two new listeners to get create user FORM and save this new user. so modify your “$(function()” block like below::
1
2
3
4
5
|
$(function() {
$(document).on("click","a#user_list",function(){ getUserList(this); });
$(document).on("click","a#create_user_form",function(){ getCreateForm(this); });
$(document).on("click","button#add_user",function(){ addUser(this); });
});
|
After this “$(function()” block add these two functions from below::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
functionaddUser(element) {
$(''#indicator'').show();
varUser =newObject();
User.name = $(''input#name'').val();
User.email = $(''input#email'').val();
User.mobile = $(''input#mobile'').val();
User.address = $(''textarea#address'').val();
varuserJson = JSON.stringify(User);
$.post(''controller.php'',
{
action:''add_user'',
user: userJson
},
function(data, textStatus) {
getUserList(element);
$(''#indicator'').hide();
},
"json"
);
}
functiongetCreateForm(element) {
varform =''<div>'';
form +=''<span><i></i> Name</span>'';
form +=''<input type="text" id="name" name="name" value=""/>'';
form +=''</div><br/><br/>'';
form +=''<div>'';
form +=''<span><i></i> Email</span>'';
form +=''<input type="text" id="email" name="email" value="">'';
form +=''</div><br/><br/>'';
form +=''<div>'';
form +=''<span><i></i> Mobile</span>'';
form +=''<input type="text" id="mobile" name="mobile" value=""/>'';
form +=''</div><br/><br/>'';
form += <div>'';
form +=''<span><i></i> Address</span>'';
form +=''<textarea row="5" id="address" name="address"></textarea>'';
form +=''</div><br/><br/>'';
form +=''<div>'';
form +=''<div>'';
form +=''<button type="button" id="add_user"><i></i> Add User</buttonv'';
form +=''</div>'';
form +=''</div>'';
$(''div#content'').html(form);
}
|
By function “getCreateForm” we are rendering a FORM for create new user. and function “addUser” send a “add_user” POST request with all given data in create FORM as JSON.
Open “Controller.php” and add below “case” block in “switch” ::
1
2
3
4
5
|
case''add_user'':
$user=newstdClass;
$user= json_decode($_POST[''user'']);
print$users->add($user);
break;
|
Here we are decoding “user” POST variable and passing this to “add” method of “User” class.
Now we have to add “add” mathod to “User” model class. so open “User.php” file and add this below method::
1
2
3
4
5
|
publicfunctionadd($user){
$sth=$this->dbh->prepare("INSERT INTO users(name, email, mobile, address) VALUES (?, ?, ?, ?)");
$sth->execute(array($user->name,$user->email,$user>mobile,$user->address));
returnjson_encode($this->dbh->lastInsertId());
}
|
Clicking on “Create” button you will get a nice looking FORM like below::
Fill up this FORM and click “Add User” button, all data will save and without page load you can see the updated user list.
Hope you already see a “red” button on user list table, it is for delete user which is in current row. So now we want to delete recently added user. Let implement the “Delete” functionality.
Open “custom.js” file and add another new two listener to it, so your “$(function()” block will look like below::
1
2
3
4
5
6
7
|
$(function() {
$(document).on("click","a#user_list",function(){ getUserList(this); });
$(document).on("click","a#create_user_form",function(){ getCreateForm(this); });
$(document).on("click","button#add_user",function(){ addUser(this); });
$(document).on("click","a.delete_confirm",function(){ deleteConfirmation(this); });
$(document).on("click","button.delete",function(){ deleteUser(this); });
});
|
After this “$(function()” block add these two functions from below::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
functiondeleteConfirmation(element) {
$("#delete_confirm_modal").modal("show");
$("#delete_confirm_modal input#user_id").val($(element).attr(''user_id''));
}
functiondeleteUser(element) {
varUser =newObject();
User.id = $("#delete_confirm_modal input#user_id").val();
varuserJson = JSON.stringify(User);
$.post(''controller.php'',
{
action:''delete_user'',
user: userJson
},
function(data, textStatus) {
getUserList(element);
$("#delete_confirm_modal").modal("hide");
},
"json"
);
}
|
Function “deleteConfirmation” will display a confirmation modal which will ask about delete user. and function “deleteUser” will delete user with given user id.
Open “Controller.php” and add below “case” block in “switch” ::
1
2
3
4
5
|
case''delete_user'':
$user=newstdClass;
$user= json_decode($_POST[''user'']);
print$users->delete($user);
break;
|
Here we are decoding “user” POST variable and passing this to “delete” method of “User” class.
Now we have to add “delete” mathod to “User” model class. so open “User.php” file and add this below method::
1
2
3
4
5
|
publicfunctiondelete($user){
$sth=$this->dbh->prepare("DELETE FROM users WHERE id=?");
$sth->execute(array($user->id));
returnjson_encode(1);
}
|
Clicking on any “Red Cross” button it will display a nice modal to get confirmation from you like below::
If you click on “No” button then modal will disappear and no server action but if you click on “Yes” button then the user will delete and you can see your updated user list.
And at last the special thing “Edition”, why special? because we will implement a inline edition now. we only use jquery but no any additional js plugin for this easy and simple and few code. So open your “custom.js” and update like below::
1
2
3
4
5
6
7
8
9
|
$(function() {
$(document).on("click","a#user_list",function(){ getUserList(this); });
$(document).on("click","a#create_user_form",function(){ getCreateForm(this); });
$(document).on("click","button#add_user",function(){ addUser(this); });
$(document).on("click","a.delete_confirm",function(){ deleteConfirmation(this); });
$(document).on("click","button.delete",function(){ deleteUser(this); });
$(document).on("dblclick","td.edit",function(){ makeEditable(this); });
$(document).on("blur","input#editbox",function(){ removeEditable(this) });
});
|
You can see we added new two listener, one on double click and another one on blur. so when we double click on any data, a editable input box will appear and after necessary change when we move the focus from this input field then it will disappear and return to as before.
So after this block now add two new functions from below::
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
functionremoveEditable(element) {
$(''#indicator'').show();
varUser =newObject();
User.id = $(''.current'').attr(''user_id'');
User.field = $(''.current'').attr(''field'');
User.newvalue = $(element).val();
varuserJson = JSON.stringify(User);
$.post(''controller.php'',
{
action:''update_field_data'',
user: userJson
},
function(data, textStatus) {
$(''td.current'').html($(element).val());
$(''.current'').removeClass(''current'');
$(''#indicator'').hide();
},
"json"
);
}
functionmakeEditable(element) {
$(element).html(''<input id="editbox" size="''+ $(element).text().length +''" type="text" value="''+ $(element).text() +''">'');
$(''#editbox'').focus();
$(element).addClass(''current'');
}
|
Open “Controller.php” and add below “case” block in “switch” ::
1
2
3
4
5
|
case''update_field_data'':
$user=newstdClass;
$user= json_decode($_POST[''user'']);
print$users->updateValue($user);
break;
|
Now we have to add “updateValue” mathod to “User” model class. so open “User.php” file and add this below method::
1
2
3
4
5
|
publicfunctionupdateValue($user){
$sth=$this->dbh->prepare("UPDATE users SET ".$user->field ."=? WHERE id=?");
$sth->execute(array($user->newvalue,$user->id));
returnjson_encode(1);
}
|
Here “updateValue” method updating data of given field.
Now if you double click on any data you will get a input field to edit this data like below::
After change when this field get lost the focus then the new data will save and it will become like before as non editable.
So those are all for this article. Thanks.
Download Source
关于解决 PHP PDO 读取 MSSQL 数据乱码问题和php读取mysql的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于1、PDO:PDO 简介、5.3 版本 php 与 5.5 公用的 pdo 技巧、Codeigniter PDO 错误连接注意:尝试获取非对象的属性文件名 pdo/pdo_driver.php、CRUD with PHP MVC, PDO, JSON and Twitter Bootstrap的相关知识,请在本站寻找。
本文标签: