<!DOCTYPE html>
	<html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
	<head>
<title>Sử dụng PDO trong lập trình NukeViet</title>
<meta name="description" content="Sử dụng PDO trong lập trình NukeViet - Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;nukeviet.edu.vn&#x002F;savefile&#x002F;Chia-se-kien-thuc-web&#x002F;Su-dung-PDO-trong-lap-trinh-NukeViet-12.html">
<meta name="author" content="Trung tâm đào tạo NukeViet">
<meta name="copyright" content="Trung tâm đào tạo NukeViet [admin@nukeviet.edu.vn]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="google-site-verification" content="kgyPa58My857f_Ag72D-SrJlLkaTD9H8UkYaCI0eDcg">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Sử dụng PDO trong lập trình NukeViet">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;nukeviet.edu.vn&#x002F;savefile&#x002F;Chia-se-kien-thuc-web&#x002F;Su-dung-PDO-trong-lap-trinh-NukeViet-12.html">
<meta property="og:site_name" content="Trung tâm đào tạo NukeViet">
<meta property="og:url" content="https://nukeviet.edu.vn/savefile/Chia-se-kien-thuc-web/Su-dung-PDO-trong-lap-trinh-NukeViet-12.html">
<link rel="shortcut icon" href="https://nukeviet.edu.vn/favicon.ico">
<link rel="canonical" href="https://nukeviet.edu.vn/savefile/Chia-se-kien-thuc-web/Su-dung-PDO-trong-lap-trinh-NukeViet-12.html">
<link rel="alternate" href="https://nukeviet.edu.vn/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://nukeviet.edu.vn/rss/Chia-se-kien-thuc-web/" title="Tin Tức - Chia sẻ kiến thức web" type="application/rss+xml">
<link rel="alternate" href="https://nukeviet.edu.vn/rss/Thong-bao/" title="Tin Tức - Thông báo" type="application/rss+xml">
<link rel="alternate" href="https://nukeviet.edu.vn/rss/Dao-tao-web/" title="Tin Tức - Đào tạo web" type="application/rss+xml">
<link rel="alternate" href="https://nukeviet.edu.vn/rss/Tin-tuc-cong-nghe/" title="Tin Tức - Tin tức công nghệ" type="application/rss+xml">
<link rel="preload" as="style" href="https://nukeviet.edu.vn/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/bootstrap.min.css" type="text/css">
<link rel="preload" as="style" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/style.responsive.css" type="text/css">
<link rel="preload" as="style" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/news.css" type="text/css">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/themes/nukeviet_edu/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/themes/nukeviet_edu/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://nukeviet.edu.vn/themes/nukeviet_edu/js/bootstrap.min.js" type="text/javascript">
<link rel="StyleSheet" href="https://nukeviet.edu.vn/assets/css/font-awesome.min.css">
<link rel="StyleSheet" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/bootstrap.min.css">
<link rel="StyleSheet" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/style.css">
<link rel="StyleSheet" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/style.responsive.css">
<link rel="StyleSheet" href="https://nukeviet.edu.vn/themes/nukeviet_edu/css/news.css">
<style type="text/css">
	body{background: #fff;}
</style>
		<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-T5KSND2');</script>
<!-- End Google Tag Manager -->

	</head>
	<body>
	<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-T5KSND2"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">Trung tâm đào tạo NukeViet</h2>
		<p class="pull-right"><a title="Trung tâm đào tạo NukeViet" href="https://nukeviet.edu.vn/">https://nukeviet.edu.vn</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Sử dụng PDO trong lập trình NukeViet</h1>
		<ul class="list-inline">
			<li>Thứ ba - 18/03/2014 04:35</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
						<div class="pull-left imghome">
				<img alt="Sử dụng PDO trong lập trình NukeViet" src="https://nukeviet.edu.vn/uploads/news/2014_03/pdo.jpg" width="100" class="img-thumbnail" />
								<p>
					<em>Sử dụng PDO trong lập trình NukeViet</em>
				</p>
			</div>
			Kể từ phiên bản NukeViet 4.0, PDO được đưa vào thay thế cho cách kết nối dữ liệu bằng API MySQL (thư viện mở rộng MySQL) như các phiên bản trước đó. Bằng cách này, NukeViet 4.0 đã có thể kết nối với nhiều loại cơ sở dữ liệu khác nhau: Mysql, MariaDB và Oracle.
		</div>
		<div id="bodytext" class="clearfix">
			<div style="line-height: 25px"><p style="text-align: justify;"><span style="font-size:14px;">PDO (PHP Data Object) là các API có sẵn của PHP cho phép người lập trình có thể kết nối để làm việc với cơ sở dữ liệu. PDO không phải là một khái niệm mới, nó được giới thiệu lần đầu tiên ở phiên bản PHP 5, hiện nay đang được sử dụng rất phổ biến. PDO là các đối tượng dữ liệu trong PHP, nó sẽ chuyển tất cả dữ liệu thành đối tượng, đồng thời cũng cung cấp các phương thức để thao tác với cơ sở dữ liệu.</span></p><p style="text-align: justify;"><span style="font-size:14px;"><strong>I. <span style="color:rgb(255, 0, 0);">Lưu ý:</span> Khi Sử dụng các đoạn code có khả năng lỗi cần viết vào try, catch</strong></span></p><p style="text-align: justify; margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">try<br  />{<br  />$db-&gt;query( &#039;&#039; );<br  />}<br  />catch( PDOException $e )<br  />{<br  />trigger_error( $e-&gt;getMessage() );<br  />}</span></span></span></p><p style="text-align: justify;"><strong style="font-size: 14px; line-height: 1.6;">II. Fetch dữ liệu</strong></p><p><span style="font-size:14px;">Có hai cách căn bản để lấy dữ liệu trong PDO là query và excute.<br  />- Query: sử dụng trong các trường hợp câu truy vấn không có biến truyền vào, hoặc các biến chắc chắn không gây ra Sql Injection</span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">$result = $db-&gt;query( &#039;select SQL_CALC_FOUND_ROWS * from nv3_config LIMIT 0, 30&#039; );<br  />$rs1 = $db-&gt;query( &#039;SELECT FOUND_ROWS()&#039; );<br  />$all_page = $rs1-&gt;fetchColumn( );<br  />print(&quot;all_page $all_page rows<br  />&quot;);<br  />foreach( $result as $row )// lặp qua từng dòng<br  />{</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">printf( &#039;module: %s&lt;br /&gt;config_name: %s &lt;p /&gt;&#039;, $row[&#039;module&#039;], $row[&#039;config_name&#039;] );</span></span></span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">}</span></span></span></p><p><span style="font-size:14px;">- Exec: sử dụng trong các trường hợp câu truy vấn không có biến truyền vào, hoặc các biến chắc chắn không gây ra Sql Injection, giá trị trả về là số dòng thực hiện.</span></p><p style="margin-left: 40px;"><span style="font-size:14px;"><span style="color:rgb(0, 0, 255);"><span style="font-family:courier new,courier,monospace;"><span style="font-size:12px;">$count = $db-&gt;exec( &quot;DELETE FROM nv3_config WHERE module = &#039;khongco&#039;&quot; );<br  />print(&quot;Deleted $count rows&quot;);</span></span></span></span></p><p><span style="font-size:14px;">Ngoài ra, còn có một cách tiếp cận khác nữa là sử dụng bindParam, phương thức này sử dụng trong trường hợp nếu có biến truyền vào câu truy vấn.</span></p><p style="margin-left: 40px;"><span style="font-size:14px;"><span style="color:rgb(0, 0, 255);"><span style="font-family:courier new,courier,monospace;"><span style="font-size:12px;">$config_name = &#039;users2&#039;;<br  />$del = $db-&gt;prepare( &#039;DELETE FROM nv3_config2 WHERE config_name=:config_name&#039; );<br  />$del-&gt;bindValue( &#039;:config_name&#039;, $config_name );<br  />$del-&gt;execute( );</span></span></span></span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-family:courier new,courier,monospace;"><span style="font-size:12px;">$module = &#039;users&#039;;<br  />$sth = $db-&gt;prepare( &quot;select * from nv3_config WHERE module=:module LIMIT 0, 4&quot; );<br  />$sth-&gt;bindParam( &#039;:module&#039;, $module );<br  />$sth-&gt;execute( );<br  />$array = $sth-&gt;fetchAll();<br  />var_export( $array );</span></span></span></p><p><strong><span style="font-size: 14px;">III. Chỉ định dữ liệu đầu ra</span></strong></p><p><span style="font-size: 14px;">Cũng như cách dùng của API mysql, dữ liệu khi được lấy ra từ cơ sở dữ liệu cần phải được “đổ” (fetch) vào một array, object hoặc một class thì mới sử dụng được. PDO cũng cung cấp một số kiểu fetch cơ bản như sau:</span></p><p style="margin-left: 40px;"><span style="font-size: 14px;">- PDO::FETCH_ASSOC: Trả về dạng mảng (array)</span></p><p style="margin-left: 40px;"><span style="font-size:14px;">- PDO::FETCH_BOTH: Trả về một mảng, key giữa tên cột và giá trị index bắt đầu từ 0<br  />- PDO::FETCH_BOUND: Trả về TRUE và gán các giá trị của các cột trong kết quả tương ứng vào các biến bạn đã thiết lập cho nó.<br  />- PDO::FETCH_CLASS: Trả lại một lớp (class)<br  />- PDO::FETCH_OBJ: Trả về một đối tượng vô danh với tên tương ứng với các cột<br  />- PDO::FETCH_NUM: (Là số 3 ) Trả về một mảng, giá trị index bắt đầu từ 0</span></p><p><span style="font-size: 14px;">Mặc định, NukeViet sử dụng PDO::FETCH_ASSOC.</span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">$sql = &#039;SELECT * FROM &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; WHERE status=1 AND id=&#039; . $id;</span></span></span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">$row = $db-&gt;query( $sql )-&gt;fetch();</span></span></span></p><p><span style="font-size: 14px; line-height: 25px;">Mặc định, NukeViet sử dụng PDO::FETCH_ASSOC.</span></p><p><strong><span style="font-size:14px;"><span style="line-height: 25px;">IV.&nbsp;</span>Thao tác dữ liệu</span></strong></p><p><em><strong><span style="font-size: 14px;">1. Create (insert)</span></strong></em></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sth = $db-&gt;prepare(&#039;INSERT INTO &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; VALUES(NULL, :name, :birthday, :class)&#039;);</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sth-&gt;bindParam(&#039;:name&#039;, $name, PDO::PARAM_STR);<br  />$sth-&gt;bindParam(&#039;:name&#039;, $birthday, PDO::PARAM_STR);<br  />$sth-&gt;bindParam(&#039;:class&#039;, $class, PDO::PARAM_STR);<br  />$sth-&gt;execute();</span></span></span></p><p><span style="font-size:14px;"><em><strong>2. Update</strong></em></span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-family:courier new,courier,monospace;"><span style="font-size:12px;">$sth = $db-&gt;prepare(&#039;UPDATE &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; SET name = :name, birthday = :birthday, class = :class)&#039;);<br  />$sth-&gt;bindParam(&#039;:name&#039;, $name, PDO::PARAM_STR);<br  />$sth-&gt;bindParam(&#039;:name&#039;, $birthday, PDO::PARAM_STR);<br  />$sth-&gt;bindParam(&#039;:class&#039;, $class, PDO::PARAM_STR);<br  />$sth-&gt;execute();</span></span></span></p><p><span style="font-size:14px;"><em><strong>3. Delete</strong></em></span></p><p style="margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sth = $db&gt;prepare(&#039;DELETE FROM &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; WHERE id = :id&#039;);<br  />$stmt-&gt;bindParam(&#039;:id&#039;, $id);<br  />$stmt-&gt;execute();</span></span></p><p><span style="font-size:14px;">Thực thi nhiều câu lệnh<br  />Xem ví dụ:&nbsp;</span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$stmt = $db-&gt;prepare(&#039;INSERT INTO &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; VALUES(:name)&#039;);<br  />$stmt-&gt;bindParam(&#039;:name&#039;, $name);<br  /># First insertion<br  />$name = &#039;Keith&#039;;<br  />$stmt-&gt;execute();</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"># Second insertion<br  />$name = &#039;Steven&#039;;<br  />$stmt-&gt;execute();</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">// Max Weight<br  />$_sql = &#039;SELECT max(weight) FROM &#039; . NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039; WHERE catid=&#039; . $catid;<br  />$weight = $db-&gt;query( $_sql )-&gt;fetchColumn();<br  />$weight = intval( $weight ) + 1;</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">// Fetch Limit<br  />$db-&gt;sqlreset()<br  />&nbsp; -&gt;select( &#039;COUNT(*)&#039; )<br  />&nbsp; -&gt;from( NV_PREFIXLANG . &#039;_&#039; . $module_data )<br  />&nbsp; -&gt;where( &#039;status=1&#039; );</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$all_page = $db-&gt;query( $db-&gt;sql() )-&gt;fetchColumn();</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$db-&gt;select( &#039;*&#039; )<br  />&nbsp; -&gt;order( &#039;id DESC&#039; )<br  />&nbsp; -&gt;limit( $per_page )<br  />&nbsp; -&gt;offset( $page );<br  />while( $row = $_query-&gt;fetch() )<br  />{<br  />&nbsp; &nbsp; //$id = $row[&#039;id&#039;];<br  />}</span></span></span></p><p><span style="font-size:14px;"><strong>V. Các chú ý trong lập trình CSDL với NukeViet</strong><br  /><em><strong>1. Về đặt tên các bảng và cột</strong></em><br  />- Tên bảng, tên cột chỉ dùng từ &nbsp;từ 2 đến 30 ký tự, chỉ dùng các ký tự a-z, 0-9 và dấu gạch dưới<br  />- Tất cả các dữ liệu các cột cần viết thường, (Nếu có viết hoa thì kết quả trả về trong các mảng khi Fetch dữ liệu cũng là các mảng có chỉ số viết thường)</span></p><p><span style="font-size:14px;"><em><strong>2. Về các câu truy vấn các cột</strong></em><br  />Thường chúng ta viết câu truy vấn chúng ta viết như sau</span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">SELECT `catid`, `parentid`, `title` FROM `nv3_vi_news_cat`</span></span></span></p><p><span style="font-size:14px;">Thì cần viết lại:</span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">SELECT catid, parentid, title FROM nv3_vi_news_cat</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Tức bỏ dấu ` đi để có thể chạy được trên các loại CSDL khác, Khi đó sẽ không dùng được các tên sau trong bảng và cột của CSDL:</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">add, all, alter, analyze, and, as, asc, before, between, bigint, binary, both, by, call, cascade, case, change, char, character, check, collate, column, comment, condition, constraint, continue, convert, create, cross, current_user, cursor, database, databases, date, day_hour, day_minute, day_second, dec, decimal, declare, default, delayed, delete, desc, describe, distinct, distinctrow, drop, dual, else, elseif, enclosed, escaped, exists, exit, explain, false, fetch, file, float4, float8, for, force, foreign, from, fulltext, get, grant, group, having, high_priority, hour_minute, hour_second, identified, if, ignore, ignore_server_ids, in, index, infile, inner, insert, int1, int2, int3, int4, int8, integer, interval, into, is, iterate, join, key, keys, kill, leading, leave, left, level, like, limit, lines, load, lock, long, loop, low_priority, master_bind, master_heartbeat_period, master_ssl_verify_server_cert, match, middleint, minute_second, mod, mode, modify, natural, no_write_to_binlog, not, null, number, numeric, on, optimize, option, optionally, or, order, outer, outfile, partition, precision, primary, privileges, procedure, public, purge, read, real, references, release, rename, repeat, replace, require, resignal, restrict, return, revoke, right, rlike, rows, schema, schemas, select, separator, session, set, share, show, signal, spatial, sql_after_gtids, sql_before_gtids, sql_big_result, sql_calc_found_rows, sql_small_result, sqlstate, ssl, start, starting, straight_join, table, terminated, then, to, trailing, trigger, true, undo, union, unique, unlock, unsigned, update, usage, use, user, using, values, varcharacter, varying, view, when, where, while, with, write, year_month, zerofill</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;"><em><strong>3. Đặt bí danh cho bảng (Table Allias)</strong></em><br  />Không dùng mệnh đề &nbsp;AS cho bảng &nbsp;(Vẫn có thể dùng Allias cho cột được)</span></p><p style="text-align: justify;"><span style="font-size:14px;">Thay vì viết</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">SELECT t1.catid, t1.parentid, t1.title FROM nv3_vi_news_cat AS t1</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Hãy viết bằng</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">SELECT t1.catid, t1.parentid, t1.title FROM nv3_vi_news_cat t1</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;"><em><strong>4. Viết câu lệnh và lấy về chỉ số tăng tự động</strong></em><br  />Trước chúng ta viết</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sql = &quot;INSERT INTO &quot; . NV_PREFIXLANG . &quot;_&quot; . $module_data . &quot;_cat<br  />(catid, parentid, title, titlesite, alias, description)<br  />VALUES<br  />(NULL, :parentid, :title, :titlesite, :alias, :description)&quot;;</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Và dùng&nbsp;</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sth = $db-&gt;prepare($sql);<br  />$sth-&gt;bindParam…..<br  />$sth-&gt;execute();</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Thì cần viết lại theo cách</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sql = &quot;INSERT INTO &quot; . NV_PREFIXLANG . &quot;_&quot; . $module_data . &quot;_cat<br  />( parentid, title, titlesite, alias, description)<br  />VALUES<br  />(:parentid, :title, :titlesite, :alias, :description)&quot;;<br  />$data_insert = array();<br  />$data_insert[&#039;parentid&#039;] = $parentid;<br  />$data_insert[&#039;title&#039;] = $title;<br  />$data_insert[&#039;titlesite&#039;] = $titlesite;<br  />$data_insert[&#039;alias&#039;] = $alias;<br  />$data_insert[&#039;description&#039;] = $description;<br  />$newcatid = $db-&gt;insert_id( $sql, &#039;catid&#039;, $data_insert );</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;"><em><strong>5. Khi câu lệnh có Limit cần sử dụng lớp $db để tạo câu lệnh SQL</strong></em></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$db-&gt;sqlreset()<br  />-&gt;select( &#039;COUNT(*)&#039; )<br  />-&gt;from( NV_PREFIXLANG . &#039;_&#039; . $module_data . &#039;_rows&#039; )<br  />-&gt;where( &#039;status= 1 AND inhome=1&#039; );</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$all_page = $db-&gt;query( $db-&gt;sql() )-&gt;fetchColumn();</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$db-&gt;select( &#039;id, catid, listcatid, topicid, admin_id, author, sourceid, addtime, edittime, publtime, title, alias, hometext, homeimgfile, homeimgalt, homeimgthumb, allowed_rating, hitstotal, hitscm, total_rating, click_rating&#039; )<br  />-&gt;order( &nbsp;&#039;id DESC&#039; )<br  />-&gt;limit( $per_page )<br  />-&gt;offset( page );</span></span></span></p><p style="margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$result = $db-&gt;query( $db-&gt;sql() );</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Ngoài ra nếu câu lệnh SQL có sử dụng SQL_CALC_FOUND_ROWS, SELECT FOUND_ROWS() để lấy tổng số kết quả truy vấn (các cách này chỉ chạy trên MySQL). Thì khi đó cần viết thành 2 câu lệnh truy vấn tương tự như trên.</span></p><p style="text-align: justify;"><span style="font-size:14px;"><em><strong>6. Không sử dụng REPLACE INTO trong câu lệnh SQL, thay vì đó hãy sử dụng INSERT hay update</strong></em><br  />Nguyên nhân REPLACE INTO chỉ dùng được trên MySQL, ngoài ta REPLACE INTO nếu chạy trên MySQL với Storage Engine InnoDB thực chất cũng dùng hai câu lệnh DELETE và INSERT cùng lúc</span></p><p style="text-align: justify;"><em><strong><span style="font-size: 14px;">7. PDOStatement :: rowCount () trả về số hàng bị ảnh hưởng bởi cuối cùng DELETE, INSERT, hoặc UPDATE thực hiện bởi các đối tượng PDOStatement tương ứng.</span></strong></em></p><p style="text-align: justify;"><span style="font-size: 14px;">Không sử dụng đối với câu lệnh SQL SELECT do trên Oracle không chạy</span></p><p style="text-align: justify;"><span style="font-size: 14px;">Nếu viết</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$result = $db-&gt;query( &quot;SELECT * FROM &quot; . $db_config[&#039;prefix&#039;] . &quot;_&quot; . $lang_data . &quot;_modules where title=&#039;news&#039;&quot; );<br  />if( $result-&gt;rowCount() )<br  />{<br  />&nbsp;&nbsp; &nbsp;//<br  />}</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;">Cần viết thành</span></p><p style="text-align: justify; margin-left: 40px;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;"><span style="font-family:courier new,courier,monospace;">$result = $db-&gt;query( &quot;SELECT COUNT(*) FROM &quot; . $db_config[&#039;prefix&#039;] . &quot;_&quot; . $lang_data . &quot;_modules where title=&#039;news&#039;&quot; );<br  />if( $result-&gt;fetchColumn() )<br  />{<br  />&nbsp;&nbsp; &nbsp;//<br  />}</span></span></span></p><p style="text-align: justify;"><span style="font-size:14px;"><em><strong>8. Sử dụng Prepares a statement</strong></em><br  />PDOStatement::bindParam, PDOStatement::bindValue đều dùng để truyền dữ liệu cho Prepares a statement, nhưng chúng khác nhau<br  />PDOStatement::bindParam&nbsp;&nbsp; &nbsp;Truyền địa chỉ của biến.<br  />PDOStatement::bindValue&nbsp;&nbsp; &nbsp;Truyền giá trị của biến.</span></p><p style="text-align: justify;"><span style="font-size:14px;">- Nên nếu dùng trong vòng lặp, mà chưa chạy PDOStatement::execute thì cần dùng PDOStatement::bindValue<br  />- Nếu cần gán giá trị &gt; 400 ký tự bắt buộc phải dùng PDOStatement::bindParam và phải có cả độ dài của chuỗi</span></p><p style="text-align: justify; margin-left: 40px;"><span style="font-family:courier new,courier,monospace;"><span style="color:rgb(0, 0, 255);"><span style="font-size:12px;">$sth = $db-&gt;prepare( &#039;UPDATE nv3_vi_news_bodyhtml SET bodyhtml = :bodyhtml WHERE id=4&#039; );<br  />$len = strlen($bodyhtml);<br  />$sth-&gt;bindParam( &#039;:bodyhtml&#039;, $bodyhtml, PDO::PARAM_STR, $len );<br  />$sth-&gt;execute();</span></span></span></p></div>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://nukeviet.edu.vn/savefile/Chia-se-kien-thuc-web/Su-dung-PDO-trong-lap-trinh-NukeViet-12.html" title="Sử dụng PDO trong lập trình NukeViet">https://nukeviet.edu.vn/savefile/Chia-se-kien-thuc-web/Su-dung-PDO-trong-lap-trinh-NukeViet-12.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; Trung tâm đào tạo NukeViet
		</div>
		<div id="contact">
			<a href="mailto:admin@nukeviet.edu.vn">admin@nukeviet.edu.vn</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://nukeviet.edu.vn/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
<script src="https://nukeviet.edu.vn/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_s5qU1",nv_check_pass_mstime=21538000,nv_area_admin=0,nv_safemode=0,theme_responsive=1,nv_recaptcha_ver=2,nv_recaptcha_sitekey="6Ler2ssZAAAAAGDHZD32W4NSMuzz3yaQLqYSu9UK",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://nukeviet.edu.vn/assets/js/language/vi.js"></script>
<script src="https://nukeviet.edu.vn/assets/js/DOMPurify/purify3.js"></script>
<script src="https://nukeviet.edu.vn/assets/js/global.js"></script>
<script src="https://nukeviet.edu.vn/assets/js/site.js"></script>
<script src="https://nukeviet.edu.vn/themes/nukeviet_edu/js/news.js"></script>
<script src="https://nukeviet.edu.vn/themes/nukeviet_edu/js/main.js"></script>
<script src="https://nukeviet.edu.vn/themes/nukeviet_edu/js/bootstrap.min.js"></script>
</body>
</html>