Mac环境下php操作mysql数据库的方法分享
Mac环境下php操作mysql数据库的方法分享
今天在mac上搭建好了php的环境,我们就把php操作mysql数据库的方法分享给大家,有需要的小伙伴参考下。
Mac本地环境搭建
在Mac系统,我们可以使用MAMP Pro 软件来搭建本地服务器。安装好这款软件,网站的目录在 /Applications/MAMP/htdocs 文件夹里,只需将文件放入该文件夹中,就可以通过http://localhost:8888来访问了,或者通过点击如下红色下划线按钮来快速访问站点。
mac系统下安装php,两行即可。
?
1 2 |
brew tap josegonzalez/homebrew-php brew install php54 |
安装完后配置一下,你就可以使用phpstorm来愉快地编程啦。安装的php路径在/usr/local/bin/php
数据库基本操作
1)用户的 Web 浏览器发出 HTTP 请求,请求特定 Web 页面。
2)Web服务器收到.php 的请求获取该文件,并将它传到 PHP 引擎,要求它处理。 3)PHP 引擎开始解析脚本。 脚本中有一条连接数据库的命令, 还有执行一个查询的令。命
PHP 打开通向 MYSQL 数据库的连接,发送适当的查询。
4)MYSQL 服务器接收数据库查询并处理。将结果返回到 PHP 引擎。
5)PHP 以你去哪干完成脚本运行,通常,这包括将查询结果格式化成 HTML 格式。然
后再输出 HTML 返回到 Web 服务器。
6)Web服务器将 HTML 发送到浏览器。
MySQL 常用数据类型
整数型:TINYINT,SMALLINT,INT,BIGINT
浮点型:FLOA T,DOUB LE,DECIMAL(M,D)
字符型:CHAR,VARCHAR
日期型:DA TETIME,DA TE,TIMESTA MP
备注型:TINYTEXT,TEXT,LONGTEXT
MySQL 数据库操作
1)显示当前存在的数据库
>SHOWDATABASES;
2)选择你所需要的数据库
>USEguest;
3)查看当前所选择的数据库
>SELECTDATABASE();
4)查看一张表的所有内容
>SELECT*FROMguest; //可以先通过SHOWTABLES;来查看有多少张表
5)根据数据库设置中文编码
>SET NAMESgbk; //set names utf8;
6)创建一个数据库
>CREATEDATABASEbook;
7)在数据库里创建一张表
>CREATETABLEusers (
>username VARCHAR(20),//NOT NULL 设置不允许为空
>sex CHAR(1),
>birth DATETIME);
8)显示表的结构
>DESCIRBEusers;
9)给表插入一条数据
?
1 |
>INSERT INTO users (username,sex,birth) VALUES('jack','male',NOW()); |
PHP连接MySQL数据库
连接数据库
?
1 2 3 4 5 6 7 |
header('COntent-Type:text/html;charset=utf-8');//设置页面编码,如果文件是gbk编码,则charset也应用gbk //@表示如果出错了,不要报错,直接忽略 //参数:服务器地址,用户名和密码
echo (!!@mysql_connect('localhost','root','*****'));//1 ?> |
我们用双感叹号!!来将资源句柄转换成布尔值,正确输出1,错误则输出错误信息。而如果前面加了@符号,
则忽略错误信息,不会输出错误信息。
对于错误消息的处理,我们可以使用mysql_error()函数来输出错误消息:
mysql_connect('localhost','root','****') or die('数据库连接失败,错误信息:'.mysql_error());//对于密码错误的提示:
数据库连接失败,错误信息:Access denied for user 'root'@'localhost' (using password: YES)
die() 函数输出一条消息,并退出当前脚本。该函数是 exit() 函数的别名。
数据库连接参数,可以用常量来存储,这样就不能被随意修改,更加安全。
?
1 2 3 4 5 6 7 8 9 |
//定义常量参数 define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PWD','345823');//密码 $connect = mysql_connect(DB_HOST,DB_USER,DB_PWD) or die('数据库连接失败,错误信息:'.mysql_error()); echo $connect;//Resource id #2 ?> |
值得注意的是,mysql_connect()括号内的常量可不能加引号,否则肯定出错。
选择指定的数据库
?
1 2 3 4 5 6 7 8 9 10 |
define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PWD','345823');//密码 define('DB_NAME','trigkit');//在phpmyadmin创建一个名为trigkit的数据库 //连接数据库 $connect = mysql_connect(DB_HOST,DB_USER,DB_PWD) or die('数据库连接失败,错误信息:'.mysql_error()); //选择指定数据库 mysql_select_db(DB_NAME,$connect) or die('数据库连接错误,错误信息:'.mysql_error());//将表名字故意写错, 提示的错误信息:数据库连接错误,错误信息:Unknown database 'trigkt' ?> |
通常不需要使用 mysql_close(),因为已打开的非持久连接会在脚本执行完毕后自动关闭
mysql_select_db(database,connection):选择MySQL数据库
获取记录集
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PWD','345823');//密码 define('DB_NAME','trigkit'); //连接数据库 $connect = mysql_connect(DB_HOST,DB_USER,DB_PWD) or die('数据库连接失败,错误信息:'.mysql_error()); //选择指定数据库 mysql_select_db(DB_NAME,$connect) or die('数据表连接错误,错误信息:'.mysql_error()); //从数据库里把表的数据提出来(获取记录集) $query = "SELECT * FROM class";//在trigkit数据库中新建一张'表' $result = mysql_query($query) or die('SQL错误,错误信息:'.mysql_error());//故意将表名写错:SQL错误,错误信息:Table 'trigkit.clas' doesn't exist ?> |
mysql_query() 函数执行一条 MySQL 查询。
输出数据
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PWD','345823');//密码 define('DB_NAME','trigkit'); //连接数据库 $connect = mysql_connect(DB_HOST,DB_USER,DB_PWD) or die('数据库连接失败,错误信息:'.mysql_error()); //选择指定数据库,设置字符集 mysql_select_db(DB_NAME,$connect) or die('数据表连接错误,错误信息:'.mysql_error()); mysql_query('SET NAMES UTF8') or die('字符集设置出错'.mysql_error()); //从数据库里把表的数据提出来(获取记录集) $query = "SELECT * FROM class"; $result = mysql_query($query) or die('SQL错误,错误信息:'.mysql_error()); print_r(mysql_fetch_array($result,MYSQL_ASSOC)); ?> |
释放结果集资源(仅需要在考虑到返回很大的结果集时会占用多少内存时调用。)
?
1 2 3 |
mysql_free_result($result); ?> |
增删改查
新增数据
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
require 'index.php'; //新增数据 $query = "INSERT INTO CLASS( name, email, point, regdate) VALUES ( '小明', 'xiaoming@163.com', 100, NOW() )";
@mysql_query($query) or die('新增错误:'.mysql_error());
?> |
我们将上面的代码保存为index.php,丢进/Applications/MAMP/htdocs/ 文件夹。将上面的代码保存为demo.php,
放进同样的目录内。Mac系统获取文件的路径很简单,只需将文件拉进终端即可显示路径名。
修改数据
我们假设要修改的数据的名称是小明,id为2,将他的point分数修改为80分,代码如下:
?
1 2 3 4 5 6 7 |
require 'index.php';
//修改数据 $query = 'UPDATE class SET point=80 WHERE id=2'; @mysql_query($query); ?> |
删除数据
?
1 2 3 4 5 6 7 8 9 |
require 'index.php';
//删除数据 $query = "DELETE FROM class WHERE id=2"; @mysql_query($query);
mysql_close(); ?> |
显示数据
?
1 2 3 4 5 6 7 8 9 10 |
require 'index.php';
//显示数据 $query = "SELECT id,name,email,regdate FROM class"; $result = mysql_query($query) or die('sql语句错误:'.mysql_error());
print_r(mysql_fetch_array($result)); mysql_close(); ?> |
或者显示指定值数据:
?
1 2 3 |
$data = mysql_fetch_array($result); echo $data['email'];//显示email echo $data['name'];//显示name |
其他常用函数
复制代码 代码如下:
mysql_fetch_lengths(): 取得结果集中每个输出的长度
mysql_field_name(): 取得结果中指定字段的字段名
mysql _fetch_row():从结果集中取得一行作为枚举数组
mysql_fetch_assoc(): 从结果集中取得一行作为关联数组
mysql_fetch_array(): 从结果集中取得一行作为关联数组,或数字数组,或二者兼有
mysql_num_rows(): 取得结果集中行的数目
mysql_num_fields():取得结果集中字段的数目
mysql_get_client_info(): 取得 MySQL 客户端信息
mysql_get_host_info(): 取得 MySQL 主机信息
mysql_get_proto_info(): 取得 MySQL 协议信息
mysql_get_server_info(): 取得 MySQL 服务器信息

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
