


Common extension functions for PHP to link to MySQL, php to link to mysql_PHP tutorial
Jul 13, 2016 am 10:16 AMCommon extension functions for PHP to link to MySQL, PHP to link to mysql
1. PHP database connection and basic operations
MySQL uses a 'client/server' architecture. Using the MySQL extension function installed by PHP and directly using the client software area to access the MySQL database server have the same principle. You need to send SQL commands to the MySQL management system and then return the results to the user.
In PHP, SQL is divided into two categories (see SQL statement classification): one is a DQL statement that returns a result set, such as select/desc table name. After execution, PHP needs to process the result set; the other is no result. Set, such as DML, DDL, etc., but the successful execution of the DML statement will have an impact on the records in the data table.
<?php<br />//連接數(shù)據(jù)庫(kù),常用參數(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ù)庫(kù),mysql_error()只在調(diào)試中使用,再部署項(xiàng)目時(shí)就不要了,不然會(huì)泄露數(shù)據(jù)庫(kù)信息<br />mysql_select_db('test') or die('選擇數(shù)據(jù)庫(kù)失敗'.mysql_error());<br /><br />//mysql_query()可以設(shè)置字符集和執(zhí)行SQL語(yǔ)句<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ì)對(duì)表的記錄有影響<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>?>
2. PHP processing select query result set
Executing the select statement in PHP returns a result set, which can be used to process each field
$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);
If you need to access the data in the result set, you can use one of the following four functions (all take the result set resource identifier as a parameter, and automatically return the next record, and return false at the end of the table)
1. mysql_fetch_row(): This function returns a result record and saves it as an ordinary index data
2. mysql_fetch_assoc(): Get a row from the result set and save it as related data
3. mysql_fetch_array(): Get a row from the result set as an associative array, a numeric array, or both. You can use MYSQL_ASSOC (associative array form), MYSQL_NUM (index array form) and MYSQL_BOTH as the second parameter to specify the returned data form.
4. mysql_fetch_object(): Get a row from the result set as an object, and each field is accessed in object mode.
Recommendation: Do not use mysql_fetch_array() without special requirements. You can use mysql_fetch_row() or mysql_fetch_assoc() to achieve the same function with high efficiency.
There are also three commonly used functions related to result sets
5. mysql_data_seek(int $num): Move the pointer of the internal result. $num is the number of rows of the new result set pointer you want to set.
6. mysql_fetch_lengths(resource <font face="NSimsun">$result</font>
): Get the length of each output in the result set
7. mysql_result(resource <font face="NSimsun">$result</font>
, int <font face="NSimsun">$row[,mixed $field]</font>
): Returns the contents of a unit in the MySQL result set. The field parameter can be the offset or field name of the field, or the field table point field name (tablename.fieldname). If a column is given an alias ('select foo as bar from...'), the alias is used instead of the column name. Calling mysql_result() cannot be mixed with other functions that process result sets.
The mysql_fetch_array() function fetches a row from the result set as an associative array, a numeric array, or both.
Returns an array based on the rows taken from the result set, or false if there are no more rows.
mysql_fetch_array(data,array_type)
Parameter data: optional. The specification specifies the data pointer to be used. This data pointer is the result of the mysql_query() function.
Parameter: array_type optional. Specifies what kind of results are returned. Optional values ??for this parameter: MYSQL_ASSOC - associative array
MYSQL_NUM - numeric array
MYSQL_BOTH - default. Produces both associative and numeric arrays.
Note: mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing data in an array as a numerical index, you can also store data as an associative index, using the field name as the key.
Example:
$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);
?>
The output is similar to:
Array
(
[0] => Adams
[LastName] => Adams
[1] => John
[FirstName] => John
[2] => London
[City] => London
)
//////////////// ///////
The mysql_fetch_assoc() function fetches a row from the result set as an associative array.
Returns an associative array based on the rows taken from the result set, or false if there are no more rows.
mysql_fetch_assoc(data)
Parameter: data (required) The data pointer to be used. The data pointer is the result returned from mysql_query().
Note: mysql_fetch_assoc() is exactly the same as using mysql_fetch_array() plus the second optional parameter MYSQL_ASSOC. It just returns an associative array. This is also how mysql_fetch_array() initially works.
Tip: If you need a numeric index in addition to a relational index, use mysql_fetch_array().
Note: The field names returned by this function are case-sensitive.
An example is as follows:
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
{
die('Could not connect: ' . mysq...the rest of the text>>
Since I didn’t see the complete code, I only tried to answer the code I saw as follows:
1. Notice: Undefined variable: db in C:\xampp\htdocs\shop\files\mysql. php on line 5
Warning: Undefined variable db (it’s not clear which line of code it is on line 5).
From the known code point of view, the reason for this error message should be that you referenced a variable (db) defined outside the function body in the function body. From the code point of view, you actually did not notice it. For the variable The problem of incorrect application of scope (global, local).
To put it simply, db cannot be found in the function select_mycx.
Solution:
(1). Pass it in with parameters.
function select_mycx($table,$by,$select_str,$number,$db)
{
.....
}
(2). Define global variable references in the parameter body:
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
This error is actually caused by the above error, because $db is not introduced correctly, so of course the query cannot be executed correctly.

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

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

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w
