Home Backend Development PHP Problem How to connect to database with PHP

How to connect to database with PHP

Sep 21, 2019 am 11:49 AM
php database connect

How to connect to database with PHP

Process-oriented implementation of database connection

<?php
                         //一、面向过程的编码风格
        //1.PHP与MySQL建立连接
            /*语法mysqli_connect(host,username,passwd,dbname,port);
            mysqli_connect()方法具有返回值,返回值就是PHP与MySQL数据库建立连接的连接对象
                *host - MySQL数据库所在的计算机的ip地址
                * username - 登陆MySQL数据库的用户名称
                * passwd - 登陆MySQL数据库的用户密码(如果密码为空则写  “” 站位)
                * dbname - 要操作的数据库的名称
                * port - MySQL数据库所使用的端口号(一般默认为3306,不建议修改哦)
            */        $connect = mysqli_connect(&#39;127.0.0.1&#39;,&#39;root&#39;,&#39;&#39;,&#39;bigspinach&#39;,&#39;3306&#39;);
        //2.PHP向MySQL数据库发送sql语句,并接收返回的结果
            //2.1 编写sql语句
                /*
                    *增删改操作返回Boolean值
                        * 增:INSERT INTO 表名 VALUES (所有字段值)    注意:主键自增字段需写成 NULL
                             INSERT INTO 表名 字段名=新字段值 WHERE 字段名=字段值
                        * 删:DELETE FROM 表名 
                             DELETE FROM  表名   WHERE 字段名=字段值  
                        * 改 :UPDATE 表名 SET 字段名=字段值      注意:这样修改会修改所有该字段的值
                             UPDATE 表名 SET 字段名=新字段值 WHERE 字段名=字段值
                    *查操作返回  结果集对象
                        (1)基本查询
                            SELECT * FROM 表名
                            SELECT 字段名1,字段名2,... FROM 表名
                        (2)条件查询
                            SELECT * FROM 表名 WHERE 字段值=字段名                  
                        (3)排序查询
                            SELECT * FROM 表名 ORDER BY 字段名
                            正序:  SELECT * FROM 表名 ORDER BY 字段名  ASC
                            倒序:SELECT * FROM 表名 ORDER BY 字段名  DESC
                        (4)模糊查询
                            SELECT * FROM 表名 WHERE 字段名 LIKE "字符串%%"
                                            字符串%字符串
                        (5)LIMIT(MySQL方言)
                            SELECT * FROM 表名 LIMIT [位置偏移量,]行数;
                            SELECT * FROM 表名 LIMIT 0,5;     查询第一行数据开始,显示5条
                    //解析查询结果(mysqli_result对象)
                        mysqli_result对象
                        * 属性
                            * $field_count 字段数量
                            * $num_rows  多少条数据记录
                        * 方法
                            *(1) mysqli_fetch_array($result,[result]);
                                *$result - 结果集对象
                                * result - 解析为数组的返回数组的方式
                                    * a.关联数组mysqli_assoc;
                                    * b索引数组mysqli_num;
                                    * c.两种数组都返回mysqli_both(默认值))
                                方法的具体使用                                $arr=new array();                                while($row=mysqli_fetch_array($result,num)){
                                    array_push($arr,$row);                              
                                         *$arr:要压入的数组
                                         * $row:循环得到的每一条数据记录                                
                                }
                            *(2) mysqli_fetch_assoc($result)  该方法返回索引数组
                             方法的具体使用                                $arr=new array();                                while($row=mysqli_fetch_assoc($result)){
                                    array_push($arr,$row);                                                                                              
                                }                   
                */          $sql = "DELETE FROM liukai ";//删除名为 liukai 的数据表
            //2.2解决中文乱码问题--固定套路 mysqli_query($connect连接对象,&#39;SET NAMES UTF8&#39;);
          mysqli_query($connect,&#39;SET NAMES UTF8&#39;);
            //2.3将sql语句发送给MySQL数据库,并接收其返回的结果          $result = mysqli_query($connect,$sql);
          //3.PHP与MySQL数据库关闭连接
          mysqli_close($connect);
    ?>
Copy after login

Simplified:

<?php
    //1.建立连接
        $connect=mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;bigspinach&#39;,&#39;3306&#39;);    //2.定义sql语句
        $sql=&#39;select * from liukai&#39;;
        mysqli_query($connect,&#39;set names utf8&#39;);    //3.发送SQL语句
        $result=mysqli_query($connect,$sql);
        $arr=array();//定义空数组
        while($row =mysqli_fetch_array($result)){            //var_dump($row);
                //array_push(要存入的数组,要存的值)
            array_push($arr,$row);
        }
        var_dump($arr);    //4.关闭连接
       mysqli_close($connect); ?>
Copy after login

Oriented to Implementing database connection in object mode

 <?php
                        //面向对象的编码风格
        //1.new一个 mysqli(host,username,passwd,dbname,port)对象 ====等同于建立连接
        //2.定义sql语句
        //3.调用mysqli 对象  的  query($sql)方法并得到其返回结果值
        //4.调用mysqli 对象 的 close()方法关闭连接
        $mysqli = new mysqli(&#39;127.0.0.1&#39;,&#39;root&#39;,&#39;&#39;,&#39;bigspinach&#39;,&#39;3306&#39;);
        $sql = "select * from  where 姓名 = liukai ";
        $mysqli -> query(&#39;set names utf8&#39;);
        $mysqli -> query($sql);
        $mysqli -> close();    ?>
Copy after login

Recommended tutorial:PHP video tutorial

The above is the detailed content of How to connect to database with PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles