PHP鏈接MySQL的常用擴(kuò)展函數(shù),php鏈接mysql
Jun 13, 2016 am 09:23 AMPHP鏈接MySQL的常用擴(kuò)展函數(shù),php鏈接mysql
一、PHP連接數(shù)據(jù)庫及基本操作
MySQL采用的是'客戶機(jī)/服務(wù)器'架構(gòu)。使用PHP安裝的MySQL擴(kuò)展函數(shù),和直接使用客戶端軟件區(qū)訪問MySQL數(shù)據(jù)庫服務(wù)器,原理一樣,都需要向MySQL管理系統(tǒng)發(fā)送SQL命令,然后將結(jié)果返回給用戶。
在PHP中,SQL分為兩類(查看SQL語句分類):一是有返回結(jié)果集的DQL語句,如select/desc 表名,執(zhí)行完畢之后,需要PHP處理結(jié)果集;二是沒有結(jié)果集的,如DML、DDL等,但是DML語句執(zhí)行成功后對數(shù)據(jù)表的記錄有影響。
//連接數(shù)據(jù)庫,常用參數(shù)是主機(jī)名、用戶名和密碼<br>$link = mysql_connect('localhost','root','123456');<br>//判斷是否連接成功<br>if(!$link)<br>{<br>die('連接失敗'.mysql.error()); //連接成功返回資源標(biāo)識(shí)符,失敗返回false,mysql_error顯示錯(cuò)誤信息<br>}<br><br>//選擇數(shù)據(jù)庫,mysql_error()只在調(diào)試中使用,再部署項(xiàng)目時(shí)就不要了,不然會(huì)泄露數(shù)據(jù)庫信息<br>mysql_select_db('test') or die('選擇數(shù)據(jù)庫失敗'.mysql_error());<br><br>//mysql_query()可以設(shè)置字符集和執(zhí)行SQL語句<br>mysql_query('set names utf-8');<br>$sql = 'insert into test(id,name) values("1","dwqs")';<br>$result = mysql_query($sql); //執(zhí)行sql返回結(jié)果集<br><br>//處理結(jié)果集,insert屬于DML,會(huì)對表的記錄有影響<br>if($result && mysql_affected_rows() > 0)<br>{<br>//mysql_insert_id()返回最后一條新紀(jì)錄的auto_increment值<br>echo '插入數(shù)據(jù)成功'.mysql_insert_id().'<br>';<br>}<br>else<br>{<br>echo '插入數(shù)據(jù)失敗,錯(cuò)誤號(hào):'.mysql_errno().'錯(cuò)誤信息:'.mysql_error().'<br>';<br>}<br><br>//關(guān)閉連接<br>mysql_close($link);<br>?>
二、PHP處理select查詢結(jié)果集
在PHP中執(zhí)行select語句返回一個(gè)結(jié)果集,可以用于對各個(gè)字段的處理
$result = mysql_query('select * from test');<br>//獲取記錄行的個(gè)數(shù)<br>$rows = mysql_num_rows($result);<br>//獲取字段個(gè)數(shù),即數(shù)據(jù)列<br>$cols = mysql_num_fields($result);
如果需要訪問結(jié)果集中的數(shù)據(jù),可以使用下列四個(gè)函數(shù)中的一個(gè)(均以結(jié)果集資源符作為參數(shù),并自動(dòng)返回下一條記錄,在表末尾時(shí)返回false)
1、mysql_fetch_row():該函數(shù)將一條結(jié)果記錄返回并以一個(gè)普通的索引數(shù)據(jù)保存
2、mysql_fetch_assoc():從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)據(jù)保存
3、mysql_fetch_array():從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組,或數(shù)字?jǐn)?shù)組,或二者兼有??梢允褂肕YSQL_ASSOC(關(guān)聯(lián)數(shù)組形式)、MYSQL_NUM(索引數(shù)組形式)和MYSQL_BOTH作為第二個(gè)參數(shù),指定返回的數(shù)據(jù)形態(tài)。
4、mysql_fetch_object():從結(jié)果集中取得一行作為對象,各個(gè)字段以對象方式訪問。
建議:沒有特殊要求,不要使用mysql_fetch_array(),可以使用mysql_fetch_row()或者mysql_fetch_assoc()實(shí)現(xiàn)同樣的功能,且效率高。
另外也有三個(gè)與結(jié)果集相關(guān)的常用函數(shù)
5、mysql_data_seek(int $num):移動(dòng)內(nèi)部結(jié)果的指針,$num是想要設(shè)定的新的結(jié)果集指針的行數(shù)。
6、mysql_fetch_lengths(resource <font face="NSimsun">$result</font>
):取得結(jié)果集中每個(gè)輸出的長度
7、mysql_result(resource <font face="NSimsun">$result</font>
, int <font face="NSimsun">$row[,mixed $field]</font>
):返回 MySQL 結(jié)果集中一個(gè)單元的內(nèi)容。字段參數(shù)可以是字段的偏移量或者字段名,或者是字段表點(diǎn)字段名(tablename.fieldname)。如果給列起了別名('select foo as bar from…'),則用別名替代列名。調(diào)用 mysql_result()不能和其它處理結(jié)果集的函數(shù)混合調(diào)用。
mysql_fetch_array() 函數(shù)從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組,或數(shù)字?jǐn)?shù)組,或二者兼有。
返回根據(jù)從結(jié)果集取得的行生成的數(shù)組,如果沒有更多行則返回 false。
mysql_fetch_array(data,array_type)
參數(shù)data:可選。規(guī)定規(guī)定要使用的數(shù)據(jù)指針。該數(shù)據(jù)指針是 mysql_query() 函數(shù)產(chǎn)生的結(jié)果。
參數(shù):array_type可選。規(guī)定返回哪種結(jié)果。該參數(shù)可選值:MYSQL_ASSOC - 關(guān)聯(lián)數(shù)組
MYSQL_NUM - 數(shù)字?jǐn)?shù)組
MYSQL_BOTH - 默認(rèn)。同時(shí)產(chǎn)生關(guān)聯(lián)和數(shù)字?jǐn)?shù)組 。
注釋:mysql_fetch_array() 是 mysql_fetch_row() 的擴(kuò)展版本。除了將數(shù)據(jù)以數(shù)字索引方式儲(chǔ)存在數(shù)組中之外,還可以將數(shù)據(jù)作為關(guān)聯(lián)索引儲(chǔ)存,用字段名作為鍵名。
例子:
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Adams'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
mysql_close($con);
?>
輸出類似:
Array
(
[0] => Adams
[LastName] => Adams
[1] => John
[FirstName] => John
[2] => London
[City] => London
)
///////////////////////
mysql_fetch_assoc() 函數(shù)從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組。
返回根據(jù)從結(jié)果集取得的行生成的關(guān)聯(lián)數(shù)組,如果沒有更多行,則返回 false。
mysql_fetch_assoc(data)
參數(shù):data(必需)要使用的數(shù)據(jù)指針。該數(shù)據(jù)指針是從 mysql_query() 返回的結(jié)果。
注釋:mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二個(gè)可選參數(shù) MYSQL_ASSOC 完全相同。它僅僅返回關(guān)聯(lián)數(shù)組。這也是 mysql_fetch_array() 初始的工作方式。
提示:如果在關(guān)聯(lián)索引之外還需要數(shù)字索引,用 mysql_fetch_array()。
注意:本函數(shù)返回的字段名是區(qū)分大小寫的。
例子如下:
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysq......余下全文>>
?
由于沒有看到完整的代碼,僅就看到的代碼試作解答如下:
1. Notice: Undefined variable: db in C:\xampp\htdocs\shop\files\mysql.php on line 5
警告:未字義的變量db(第5行不太清楚是哪行代碼)。
這個(gè)錯(cuò)誤提示,從已知的代碼來看,其原因應(yīng)該是你在函數(shù)體里引用了一個(gè)函數(shù)體外定義的變量(db),從代碼看其實(shí)就是沒有注意到, 對于變量 作用域范圍(全局、局部)錯(cuò)誤應(yīng)用的問題。
簡單的說,函數(shù) select_mycx 里找不到 db。
解決辦法:
(1). 用參數(shù)傳遞進(jìn)去。
function select_mycx($table,$by,$select_str,$number,$db)
{
.....
}
(2). 在參數(shù)體里定義全局變量引用:
function select_mycx($table,$by,$select_str,$number)
{
global $db;
....
}
2.Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\shop\files\mysql.php on line 5
這個(gè)錯(cuò)誤實(shí)際上是上面的錯(cuò)誤引起的,因?yàn)?db沒有正確引入,所以再 query 當(dāng)然不能正確執(zhí)行。
?

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

CTE is a temporary result set in MySQL used to simplify complex queries. It can be referenced multiple times in the current query, improving code readability and maintenance. For example, when looking for the latest orders for each user in the orders table, you can first obtain the latest order date for each user through the CTE, and then associate it with the original table to obtain the complete record. Compared with subqueries, the CTE structure is clearer and the logic is easier to debug. Usage tips include explicit alias, concatenating multiple CTEs, and processing tree data with recursive CTEs. Mastering CTE can make SQL more elegant and efficient.

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

When using PHP preprocessing statements to execute queries with IN clauses, 1. Dynamically generate placeholders according to the length of the array; 2. When using PDO, you can directly pass in the array, and use array_values to ensure continuous indexes; 3. When using mysqli, you need to construct type strings and bind parameters, pay attention to the way of expanding the array and version compatibility; 4. Avoid splicing SQL, processing empty arrays, and ensuring data types match. The specific method is: first use implode and array_fill to generate placeholders, and then bind parameters according to the extended characteristics to safely execute IN queries.

There are three key ways to avoid the "undefinedindex" error: First, use isset() to check whether the array key exists and ensure that the value is not null, which is suitable for most common scenarios; second, use array_key_exists() to only determine whether the key exists, which is suitable for situations where the key does not exist and the value is null; finally, use the empty merge operator?? (PHP7) to concisely set the default value, which is recommended for modern PHP projects, and pay attention to the spelling of form field names, use extract() carefully, and check the array is not empty before traversing to further avoid risks.

WhensettingupMySQLtables,choosingtherightdatatypesiscrucialforefficiencyandscalability.1)Understandthedataeachcolumnwillstore—numbers,text,dates,orflags—andchooseaccordingly.2)UseCHARforfixed-lengthdatalikecountrycodesandVARCHARforvariable-lengthdata

The method of using preprocessing statements to obtain database query results in PHP varies from extension. 1. When using mysqli, you can obtain the associative array through get_result() and fetch_assoc(), which is suitable for modern environments; 2. You can also use bind_result() to bind variables, which is suitable for situations where there are few fields and fixed structures, and it is good compatibility but there are many fields when there are many fields; 3. When using PDO, you can obtain the associative array through fetch (PDO::FETCH_ASSOC), or use fetchAll() to obtain all data at once, so the interface is unified and the error handling is clearer; in addition, you need to pay attention to parameter type matching, execution of execute(), timely release of resources and enable error reports.
