Table of Contents
Sharing how to operate mysql database with PHP under Mac environment, macmysql
Home Backend Development PHP Tutorial Sharing 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_PHP tutorial

Jul 13, 2016 am 09:54 AM
mac mysql php

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

Copy after login

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());
Copy after login

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

Copy after login

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;> 
Copy after login

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;> 
Copy after login

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;> 
Copy after login

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;> 
Copy after login

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

Copy after login

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

Copy after login

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

Copy after login

Delete data

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

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

  mysql_close();
&#63;>

Copy after login

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

Copy after login

Or display specified value data:

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

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

CakePHP Useful Resources CakePHP Useful Resources Sep 10, 2024 pm 05:27 PM

The following resources contain additional information on CakePHP. Please use them to get more in-depth knowledge on this.

See all articles