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 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.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.
