search
HomeBackend DevelopmentPHP TutorialSharing how to operate mysql database with PHP under Mac environment, macmysql_PHP tutorial

Sharing how to operate mysql database with PHP under Mac environment, macmysql

Mac local environment setup

On Mac system, we can use MAMP Pro software to build a local server. After installing this software, the directory of the website is in the /Applications/MAMP/htdocs folder. Just put the file into the folder and you can access it through http://localhost:8888, or click on the red color below Underline buttons for quick site access.

To install php under mac system, just two lines.

brew tap josegonzalez/homebrew-php
brew install php54

After installation and configuration, you can use phpstorm to program happily. The installed php path is /usr/local/bin/php

Basic database operations

1) The user's web browser issues an HTTP request to request a specific web page.
2) The web server receives the .php request to obtain the file, and passes it to the PHP engine, asking it to process it. 3) The PHP engine starts parsing the script. The script contains a command to connect to the database and a command to execute a query. Life
PHP opens a connection to the MYSQL database and sends the appropriate query.
4) The MYSQL server receives the database query and processes it. Return results to the PHP engine.
5) PHP runs the script as you go. Typically, this involves formatting the query results into HTML format. Ran
Then output HTML back to the web server.
6) The web server sends HTML to the browser.
MySQL common data types

Integer type: TINYINT, SMALLINT, INT, BIGINT
Floating point type: FLOA T, DOUB LE, DECIMAL(M,D)
Character type: CHAR, VARCHAR
Date type: DA TETIME, DA TE, TIMESTA MP
Remark type:TINYTEXT,TEXT,LONGTEXT
MySQL database operations

1) Display the currently existing database
>SHOWDATABASES;
2) Select the database you need
>USEguest;
3) View the currently selected database
>SELECTDATABASE();
4) View all contents of a table
>SELECT*FROMguest; //You can first check how many tables there are through SHOWTABLES;
5) Set Chinese encoding according to the database
>SET NAMESgbk; //set names utf8;
6) Create a database
>CREATEDATABASEbook;
7) Create a table in the database
>CREATETABLEusers (
>username VARCHAR(20),//NOT NULL setting is not allowed to be empty
>sex CHAR(1),
>birth DATETIME);
8) Display the structure of the table
>DESCIRBEusers;

9) Insert a piece of data into the table
 

>INSERT INTO users (username,sex,birth) VALUES('jack','male',NOW());

PHP connects to MySQL database

Connect to database

<&#63;php
  header('COntent-Type:text/html;charset=utf-8');//设置页面编码,如果文件是gbk编码,则charset也应用gbk
  //@表示如果出错了,不要报错,直接忽略
  //参数:服务器地址,用户名和密码

  echo (!!@mysql_connect('localhost','root','*****'));//1
&#63;> 

We use double exclamation marks!! to convert the resource handle into a Boolean value, and output 1 if it is correct, and an error message if it is incorrect. If the @ symbol is added in front, the error message will be ignored and no error message will be output.

For error message processing, we can use the mysql_error() function to output the error message:

mysql_connect('localhost','root','****') or die('Database connection failed, error message: '.mysql_error()); // Tips for wrong password: Database connection failed, Error message: Access denied for user 'root'@'localhost' (using password: YES)
The die() function outputs a message and exits the current script. This function is an alias for the exit() function.

Database connection parameters can be stored as constants, so they cannot be modified at will and are safer.

<meta charset="utf-8">
<&#63;php
  //定义常量参数
  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 
&#63;> 

It is worth noting that the constants in the brackets of mysql_connect() cannot be quoted, otherwise an error will occur.

Select the specified database

<&#63;php
  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'
&#63;> 

Normally there is no need to use mysql_close() because the opened non-persistent connection will be automatically closed after the script is executed

mysql_select_db(database,connection): Select MySQL database

Get record set

<meta charset="utf-8">
<&#63;php
  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
&#63;> 

The mysql_query() function executes a MySQL query.

Output data

<meta charset="utf-8">
<&#63;php
  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));
&#63;> 

Release result set resources (only needs to be called when considering how much memory will be used when returning a large result set.)

<&#63;php
  mysql_free_result($result); 
&#63;>

Add, delete, modify and check

New data

<&#63;php
  require 'index.php';
  //新增数据
  $query = "INSERT INTO CLASS(
       name,
       email,
       point,
       regdate)
    VALUES (
    '小明',
    'xiaoming@163.com',
    100,
    NOW()
    )";

  @mysql_query($query) or die('新增错误:'.mysql_error());

&#63;>

We save the above code as index.php and throw it into the /Applications/MAMP/htdocs/ folder. Save the above code as demo.php and put it in the same directory. It is very simple for Mac system to obtain the path of a file. Just pull the file into the terminal and the path name will be displayed.

Modify data

We assume that the name of the data to be modified is Xiao Ming, the id is 2, and his point score is modified to 80 points. The code is as follows:

<&#63;php
  require 'index.php';

  //修改数据
  $query = 'UPDATE class SET point=80 WHERE id=2';
  @mysql_query($query);
&#63;>

Delete data

<&#63;php
  require 'index.php';

  //删除数据
  $query = "DELETE FROM class WHERE id=2";
  @mysql_query($query);

  mysql_close();
&#63;>

Show data

<&#63;php
  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();
&#63;>

Or display specified value data:

$data = mysql_fetch_array($result);
echo $data['email'];//显示email
echo $data['name'];//显示name

Other commonly used functions

Copy code The code is as follows:
mysql_fetch_lengths(): Get the length of each output in the result set
mysql_field_name(): Get the field name of the specified field in the result

mysql _fetch_row(): Get a row from the result set as an enumeration array
mysql_fetch_assoc(): Get a row from the result set as an associative array
mysql_fetch_array(): Gets a row from the result set as an associative array, a numeric array, or both

mysql_num_rows(): Get the number of rows in the result set
mysql_num_fields(): Get the number of fields in the result set

mysql_get_client_info(): Get MySQL client information
mysql_get_host_info(): Get MySQL host information
mysql_get_proto_info(): Get MySQL protocol information
mysql_get_server_info(): Get MySQL server information

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/997908.htmlTechArticleSharing the method of operating mysql database with php in Mac environment. The macmysql Mac local environment is built on the Mac system. We can use MAMP Pro software to build a local server. Install this software,...
Statement
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
ip与mac绑定什么意思ip与mac绑定什么意思Mar 09, 2023 pm 04:44 PM

ip与mac绑定是指将特定的IP地址与特定的MAC地址关联起来,使得只有使用该MAC地址的设备才能够使用该IP地址进行网络通信。ip与mac绑定可以防止被绑定的主机的IP地址不被假冒,前提条件:1、MAC地址是唯一的,并且不可假冒;只能绑定与路由器直接相连的网络上的主机(也就是主机的网关在路由器上)。

mac版下载是什么意思mac版下载是什么意思Mar 06, 2023 am 09:52 AM

mac版下载的意思是当软件在选择安装时,选择MAC版下载;Windows版和MAC版是两个不同的操作系统,所以大多数软件在选择安装的同时需要选择Windows版还是MAC版。

mac鼠标滚轮相反怎么办mac鼠标滚轮相反怎么办Mar 16, 2023 pm 05:44 PM

mac鼠标滚轮相反的解决办法:1、打开mac电脑,点击屏幕的苹果标志,然后选择“系统偏好设置”;2、在“系统偏好设置”窗口中,选择“鼠标”;3、在“鼠标”窗口中,将“滚动方向:自然”前面的勾去掉即可。

修复文件共享在 MacOS Ventura 中不起作用修复文件共享在 MacOS Ventura 中不起作用Apr 13, 2023 am 11:34 AM

修复 SMB 文件共享在 MacOS Ventura 中不起作用的问题从  Apple 菜单打开 Mac 上的“系统设置”应用程序转到“常规”,然后转到“共享”找到“文件共享”的开关并将其关闭通过转到  Apple 菜单并选择重新启动来重新启动 Mac重新启动后,返回共享系统设置面板并将“文件共享”重新设置为打开位置像往常一样恢复文件共享,它应该按预期工作如果 MacOS Ventura Mac 与另一台 Mac 或设备之间的文件共享突然再次停止工作,您可能需要在几天后或随机重复此过程。

如何防止 Mac 在显示器关闭时进入睡眠状态 (MacOS Ventura)如何防止 Mac 在显示器关闭时进入睡眠状态 (MacOS Ventura)Apr 13, 2023 pm 12:31 PM

显示器关闭时如何防止 Mac 休眠如果您希望 Mac 显示器能够在整个计算机不进入睡眠状态的情况下关闭,请在此处进行适当的设置调整:下拉  Apple 菜单并转到“系统设置”转到“显示”点击“高级...”切换“防止显示器关闭时电源适配器自动休眠”的开关现在 Mac 显示屏可以关闭,同时防止 Mac 本身进入睡眠状态。这可能主要与 Mac 笔记本电脑用户相关,但即使是那些没有 MacBook 的用户也可能会发现该功能很有用。

mac克隆是什么意思mac克隆是什么意思Jan 31, 2023 am 10:33 AM

mac克隆全称mac地址克隆,是固化在网卡上串行EEPROM中的物理地址,通常有48位长。mac克隆一般应用在路由器上,用户在用电脑直接拨号上网,后来又加了个路由器,通过路由器来实现多台电脑同时上网,这时要用到mac地址克隆了,就是把当前的电脑的mac地址克隆到路由器中去,因为运营商是把你的电脑mac地址绑定你的账号的,所以得克隆以后才能用。

mac的shift键是哪个键mac的shift键是哪个键Mar 13, 2023 pm 02:20 PM

mac的shift键是fn键上方、caps lock键下方的一个键,该键在键盘最左侧,由右下往上数第2个键;shift键是键盘中的上档转换键,可以通过“Ctrl+Shift”组合键来切换输入法。

mac解压rar用什么软件mac解压rar用什么软件Mar 03, 2023 pm 04:18 PM

mac解压rar的软件:1、The Unarchiver,是一款完全免费、小巧,而且非常易于使用的压缩、解压缩小工具;2、Keka,是一款免费、实用的压缩、解压缩工具,支持解压缩RAR格式的压缩包;3、360压缩大师,是一款免费的压缩、解压缩软件,完全支持RAR文件解压;4、MacZip,支持包括RAR在内的超过20种压缩格式的解压;5、BetterZip;6、FastZip。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool