MYSQL & PHP Referance - Jan Zumwalt

Embed Size (px)

Citation preview

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    1/43

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    2/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 2 of 43

    Table of Contents

    PHP COMMUNICATIONS WITH MYSQL........................ ...................... ......................... ......................... ...... 4SELECT & WHERE SYNTAX................. ......................... ...................... ......................... ......................... ...... 5MYSQL SIMPLE EXAMPLES ......................... ........................ ....................... ......................... ...................... 6

    STEP 1: CONNECT.................................................................................................................................................... 6STEP 2: QUERY......................................................................................................................................................... 6STEP 3: FETCH RESULTS........................................................................................................................................ 6STEP 4: EXTRACT INFORMATION FROM FETCH.................................................................................................. 6SPECIFIC ROW DATA............................................................................................................................................... 6ROW COUNT..............................................................................................................................................................6CLOSE CONNECTION............................................................................................................................................... 7

    SIMPLE DATABASE EXAMPLE....................... ......................... ......................... ...................... .................... 8MYSQL DEBUG EXAMPLES...... ...................... ......................... ......................... ...................... .................. 12

    EXAMPLE1: Hide mysql array values in html comment section.................................................................... 12DATA TYPES........ ......................... ......................... ...................... ......................... ......................... ............ 13

    NUMERIC ...................................................................................................................................................................... 13GEO SPATIAL............................................................................................................................................................... 13FUNCTIONS ......................... ......................... .......................... ...................... ......................... .................... 14

    TEXT.............................................................................................................................................................................. 14SYSTEM INFO ...................... .......................... ........................ ....................... ......................... .................... 14PRIVILEGES......................... ......................... .......................... ...................... ......................... .................... 16

    User Privileges............................................................................................................................................................. 16Admin Privileges.......................................................................................................................................................... 16GRANT .......................................................................................................................................................................... 16PASSWORD.................................................................................................................................................................. 16

    COMMANDS......................... ......................... .......................... ...................... ......................... .................... 17AS.................................................................................................................................................................................. 17CREATE ........................................................................................................................................................................ 17COUNT .......................................................................................................................................................................... 17DELETE......................................................................................................................................................................... 17DISTINCT ...................................................................................................................................................................... 17INSERT.......................................................................................................................................................................... 17LIKE............................................................................................................................................................................... 17ORDER BY.................................................................................................................................................................... 17PASSWORD.................................................................................................................................................................. 17SELECT......................................................................................................................................................................... 17UPDATE ........................................................................................................................................................................ 17WHERE ......................................................................................................................................................................... 17ALTER........................................................................................................................................................................... 17ADD COLUMN .............................................................................................................................................................. 17CHANGE COLUMN....................................................................................................................................................... 17DROPCOLUMN............................................................................................................................................................. 17ADD INDEX ................................................................................................................................................................... 17DROP INDEX................................................................................................................................................................. 17RENAME AS .................................................................................................................................................................17

    ENGINES ...................... ......................... ......................... ...................... ......................... ......................... .... 17MyISAM......................................................................................................................................................................... 17Memory (heap) ............................................................................................................................................................. 17Merge ............................................................................................................................................................................ 17InnoDB.......................................................................................................................................................................... 17Archive.......................................................................................................................................................................... 17Federated...................................................................................................................................................................... 17NDBCLUSTER (NDB) ................................................................................................................................................... 17CSV ...............................................................................................................................................................................17Blackhole...................................................................................................................................................................... 17Example ........................................................................................................................................................................ 17

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    3/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 3 of 43

    USER OPERATIONS ..................... ......................... ...................... ......................... ......................... ............ 19DATABASE OPERATIONS ...................... ......................... ......................... ...................... ......................... . 21TABLE OPERATIONS ...................... ......................... ......................... ......................... ...................... ......... 22COLUMN OPERATIONS ....................... ......................... ...................... ......................... ......................... .... 23ROW OPERATIONS (SELECT) ..................... ......................... ....................... ......................... .................... 24

    Where conditions......................................................................................................................................................... 24

    COUNT, SUM, MAX.................... ...................... ......................... ......................... ...................... .................. 26PHP & REGEX SEARCHS ..................... ......................... ...................... ......................... ......................... .... 27JOIN UNION GROUP....................... ......................... ...................... ......................... ......................... .... 28

    Test db setup: .............................................................................................................................................................. 28JOIN(default), INNER JOIN, and WHERE ................................................................................................................... 29LEFT JOIN..................................................................................................................................................................... 30RIGHT JOIN ..................................................................................................................................................................31FULL JOIN, FULL OUTER JOIN, CROSS JOIN .......................................................................................................... 32UNION ........................................................................................................................................................................... 33GROUP.......................................................................................................................................................................... 34

    DATE & TIME FUNCTIONS ...................... ......................... ......................... ...................... ......................... . 35

    Date Datatypes........................................................................................................................................................... 36DATE_FORMAT()........................................................................................................................................................ 36Extraction Functions ................................................................................................................................................... 38Getting the Current Date and Time......................................................................................................................... 38Changing Date Values............................................................................................................................................... 39

    USING PHP STATEMENTS ...................... ......................... ......................... ...................... ......................... . 40MYSQL FUNCTIONS ..................... ......................... ...................... ......................... ......................... ............ 41

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    4/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 4 of 43

    PHP COMMUNICATIONS WITH MYSQL

    What is PHP's mysqli Extension?The mysqliextension, or as it is sometimes known, the

    MySQL improvedextension, was developed to take advantage of new features found in MySQL

    systems versions 4.1.3 and newer. The mysqliextension is included with PHP versions 5 andlater.

    The mysqliextension has a number of benefits, the key enhancements over the mysqlextension being: Object-oriented interface, Support for Prepared Statements, Support for

    Multiple Statements, Support for Transactions, Enhanced debugging capabilities, Embeddedserver support.

    Comments

    # comment to end of line

    -- comment to end of line

    /* This is a multi-line

    comment */

    To login OS shell use -h only if needed.

    mysql/path/mysql -h hostname -u root -p

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    5/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 5 of 43

    SELECT & WHERE SYNTAX

    Syntaxt1, t2 are TABLE names

    c1, c2 are COLUMN or FIELD names$result is a resource OBJECT

    $rows is an array of records

    $rowis a single RECORD$dbis a database object

    Simple statement

    SELECT * FROMt1

    Advanced statement

    SELECT ALIASE

    FROM

    WHEREexpAND|ORexpAND|ORexp...

    ORDER BY

    MySQL WHERE

    The WHERE exp is used to MODIFY, DELETE, SELECT, or UPDATE SQL query operations.

    WHEREexpAND|ORexpAND|ORexp...

    where exp can be one of the following:

    column = value equal

    column != value not equal

    column > value more than

    column >= value more than or equal to

    column < value less than

    column

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    6/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 6 of 43

    MYSQL SIMPLE EXAMPLES

    STEP 1: CONNECT

    The following examples assume a db connection has been made using the following code

    echo "Test 1";

    $host = "localhost"; $user = "root"; $pwd = "";$db = mysqli_connect($host, $user, $pwd);

    mysqli_select_db($db, "test");

    STEP 2: QUERY

    Next, you must query the database for a result set. The result set is unusable until a fetch is used (nextstep)

    $query = "SELECT * FROM t1 WHERE fname = Mickey"; // single row (1d array)

    $result = mysqli_query($db, $query) or die(mysqli_error($db));

    or multiple rows would be like this

    $query = "SELECT * FROM t1"; // multiple rows (2d array)

    $result = mysqli_query($db, $query) or die(mysqli_error($db));

    STEP 3: FETCH RESULTS

    There are four ways to fetch the results...

    $row = mysqli_fetch_row($result)) // indexed single row

    $rows = mysqli_fetch_array($result)) // (both) index and/or assoc array

    $rows = mysqli_fetch_assoc($result)) // assoc array

    $rows = mysqli_fetch_object($result)) // result array as object

    STEP 4: EXTRACT INFORMATION FROM FETCH

    There are two ways to extract the information. If the information was fetched as an index than array numberswill be used to access field values. If the information was fetched as an assoc, than field names may be used.

    echo First name is . $row[2]; // indexed row: Mickey

    echo First name is . $rows[2]; // indexed array: Mickey or current row name

    echo First name is . $rows[fname]; // assoc array: Mickey or current row name

    SPECIFIC ROW DATA

    When an assoc or indexed array is being accessed, each row of information is incremented by each FETCH call. A chosen row ofinformation may be accessed by using

    SELECT * FROM t1 LIMIT 2, 1 -- use query to return 1 row after 2nd row

    or

    mysqli_data_seek($result, 2); -- use seek before fetch to return desired row

    $row = mysqli_fetch_row($result);

    ROW COUNT

    $result = mysql_query(SELECT * FROM t1);

    $row_cnt = $result->num_rows;

    or

    $result = mysql_query(SELECT * FROM t1);

    $row_cnt = mysql_num_rows($result);

    or

    $result = mysql_query(SELECT * FROM t1);

    $row_cnt = mysqli_num_rows($result);

    or

    $result = mysql_query(SELECT count(*) as num_rows FROM t1);

    $row_count = mysql_fetch_array($result);

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    7/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 7 of 43

    or

    $result = mysql_query(SELECT count(distinct c1) as distinct_items FROM t1);

    CLOSE CONNECTION

    mysql_close($db);

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    8/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 8 of 43

    SIMPLE DATABASE EXAMPLE

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    9/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 9 of 43

    update_by VARCHAR(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name',note VARCHAR(255) DEFAULT 'na' )";

    $result=mysqli_query($db,$sql_maketbl) or die(mysqli_error());

    // $sql_add_data="INSERT INTO `test_db`.`people`(`id`, `name`, `age`, `updated`, `update_by`, `note`)

    VALUES

    (NULL, 'Mickey Mouse', '50', CURRENT_TIMESTAMP, 'janz' , 'na'),(NULL, 'Mini Mouse' , '50', CURRENT_TIMESTAMP, 'janz' , 'na'),

    (NULL, 'Daffy' , '51', CURRENT_TIMESTAMP, 'unknown', 'na')";$result=mysqli_query($db,$sql_add_data) or die(mysqli_error());

    // $sql_update="SELECT * FROM `test_db`.`people`

    WHERE name LIKE 'M%' ";$result=mysqli_query($db,$sql_update) or die(mysqli_error());

    $cnt=mysqli_num_rows($result);echo"There are $cnt records with names starting with 'M'.";

    // $sql_update="UPDATE `test_db`.`people`

    SET `age` = '36'

    WHERE `name` LIKE '%Mini%' ";$result=mysqli_query($db,$sql_update) or die(mysqli_error());

    // $sql_update="DELETE FROM `test_db`.`people`

    WHERE `name` LIKE '%Daffy%' ";$result=mysqli_query($db,$sql_update) or die(mysqli_error());

    // $sql_update="SELECT * FROM `test_db`.`people` ";$result=mysqli_query($db,$sql_update) or die(mysqli_error());

    echo"";while($row=mysqli_fetch_assoc($result)){

    echoprint_r($row);}

    echo"";

    // $database="test_db";$result=mysqli_select_db($db,$database) or die(mysqli_error());

    $loop=mysqli_query($db,"SHOW TABLES FROM$database") or die('SHOW TABLES: cannot select tables');

    // $tborder = '#bb4400'; $strip1 = '#994400'; $strip2 = '#aa6622'; // orange table theme$tborder='#334499';$strip1='#3388bb';$strip2='#2266aa';// blue table theme

    while($table=mysqli_fetch_array($loop)){

    echo"

    ".$table[0]."
    table structure

    Field

    Type : LengthKeyIndexDefault

    Extra";

    $i=0;//row counter$row=mysqli_query($db,"SHOW columns FROM ".$table[0])or die('cannot select table fields');

    while($col=mysqli_fetch_array($row)){echo"".$col[0]."

    ".$col[1]."

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    10/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 10 of 43

    ".$col[2]."".$col[3]."".$col[4]."

    ".$col[5]."";

    $i++;

    }//end row loop

    echo"
    ";}//end table loop

    echo"
    ";

    // $sql_list_tables="DESCRIBE `people` ";$result=mysqli_query($db,$sql_list_tables) or die(mysqli_error());

    while($row=mysqli_fetch_assoc($result)){

    $str=implode(",",$row);

    echo$str."
    ";}

    echo"
    ";

    //

    $sql_list_tables="SHOW CREATE TABLE `people` ";$result=mysqli_query($db,$sql_list_tables) or die(mysqli_error());

    echo"
    ";while($row=mysqli_fetch_assoc($result)){

    echoprint_r($row)."
    ";}

    echo"
    ";

    // mysqli_close($db);

    echo'Mysql connection closed, end of program.';

    echo"";

    ?>

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    11/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 11 of 43

    Output

    There are 2 records with names starting with 'M'.

    Array

    (

    [id] => 1

    [name] => Mickey Mouse

    [age] => 50

    [updated] => 2012-02-06 22:09:52[update_by] => janz

    [note] => na

    )

    1Array

    (

    [id] => 2

    [name] => Mini Mouse

    [age] => 36

    [updated] => 2012-02-06 22:09:52

    [update_by] => janz

    [note] => na

    )

    1

    people

    table structure

    FieldType :

    LengthKey Index Default Extra

    id int(11) NO PRI auto_increment

    name varchar(25) YES

    age int(3) YES

    updated timestamp NO CURRENT_TIMESTAMPon update

    CURRENT_TIMESTAMP

    update_by varchar(25) NO unknown

    note varchar(255) YES na

    id,int(11),NO,PRI,,auto_increment

    name,varchar(25),YES,,,

    age,int(3),YES,,,

    updated,timestamp,NO,,CURRENT_TIMESTAMP,on update CURRENT_TIMESTAMP

    update_by,varchar(25),NO,,unknown,

    note,varchar(255),YES,,na,

    Array

    (

    [Table] => people

    [Create Table] => CREATE TABLE `people` (

    `id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(25) DEFAULT NULL COMMENT 'first name',

    `age` int(3) DEFAULT NULL COMMENT 'yrs',`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

    COMMENT 'last update',

    `update_by` varchar(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name',

    `note` varchar(255) DEFAULT 'na',

    PRIMARY KEY (`id`)

    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

    )

    1

    Mysql connection closed, end of program.

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    12/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 12 of 43

    MYSQL DEBUG EXAMPLES

    EXAMPLE1: Hide mysql array values in html comment section

    '';

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    13/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 13 of 43

    DATA TYPESNUMERIC COMMON DATA TYPES

    CHARStores up to 255 characters. You have to specify the maximum amount of characters that you will be puttinghere when you create your column.

    LONG VARCHAR Up to 2 GB of characters.

    BIT Holds a value of 0 or 1 (Boolean). It is primarily used for yes/no and true/false issues.

    FLOAT This type holds decimal numbers. It is primarily used for mathematical purposes.

    INT This stores whole numbers between -2,147,483,648 and 2,147,483,648.

    SMALLINT As above except you are l imited to numbers between -32,768 and 32,768.

    DATE This will store a date.

    DATETIMEThis will store a date and time (timestamp). It is primarily used to Time Stamp entries or updates to a row ortable.

    More... There are at least 5 date, 15 text, 8 numeric, 20 accounting data types.

    GEO SPATIAL COMMON DATA TYPES

    GEOMETRY GEOMETRY can store geometry values of any type

    GEOMETRYCOLLECTION .

    LINESTRING particular geometry type.

    MULTILINESTRINGMULTIPOINT

    MULTIPOLYGON

    POINT particular geometry type.

    POLYGON particular geometry type.

    OPERATOR Comparison

    = Compares the data to your criteria to see if it is equal

    Compares the data to your criteria to see if it is not equal

    < Compares the data to your criteria to see if the data is less than your criteria

    Compares the data to your criteria to see if the data is greater than your criteria

    >= Compares the data to your criteria to see if the data is greater than or equal to your criteriaIS NULL Checks the data to make sure that there is no data in the column

    NOT NULL Requires a value in the column, often used for key fields.

    OR Connects multiple condition tests

    AND Connects multiple condition tests

    % Wildcard, match all characters before

    _ Wildcard

    [ ] Wildcard

    OPERATOR Sorting

    ASC Sort by scending order A to Z

    DESC Sort by descending order Z to A

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    14/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 14 of 43

    FUNCTIONSNUMERIC SYNTAX EXAMPLE

    ABS() Returns the absolute value of numeric expression. SELECT ABS(-2);return: 2

    ACOS() Returns the arccosine of numeric expression. Returns

    NULL if the value is not in the range -1 to 1.

    SELECT ACOS(1);

    return: 0.000000ASIN() Returns the arcsine of numeric expression. Returns

    NULL if value is not in the range -1 to 1SELECT ASIN(1);

    return: 1.5707963267949

    ATAN() Returns the arctangent of numeric expression. SELECT ATAN(1);

    return: 0.78539816339745

    ATAN2() Returns the arctangent of the two variables passed toit.

    SELECT ATAN2(3,6);

    return: 0.46364760900081

    BIT_AND() Returns the bitwise AND all the bits in expression. SELECTMAKER, BIT_AND(PRICE) BITS

    FROM CARS GROUP BY MAKER

    return:

    MAKER BITS

    --------------

    CHRYSLER 512

    FORD 12488

    HONDA 2144BIT_COUNT() Returns the string representation of the binary value

    passed to it.SELECT

    BIT_COUNT(2) AS TWO,

    BIT_COUNT(4) AS FOUR,

    BIT_COUNT(7) AS SEVEN

    return:

    | TWO | FOUR | SEVEN |

    | 1 | 1 | 3 |

    BIT_OR() Returns the bitwise OR of all the bits in the passedexpression.

    SELECT

    MAKER, BIT_OR(PRICE) BITS

    FROM CARS GROUP BY MAKER

    return:

    MAKER BITS

    --------------

    CHRYSLER 62293

    FORD 16127

    HONDA 32766

    CEIL()CEILING()

    Returns the smallest integer value that is not less thanpassed numeric expression

    SELECT CEILING(3.46);

    return: 4

    CONV(N,from_base,to_base)

    Convert numeric expression from one base toanother.

    SELECT CONV(5,16,2);

    return: 101

    COS() Returns the cosine of passed numeric expression.The numeric expression should be expressed inradians.

    SELECT COS(90);

    return: -0.44807361612917

    COT() Returns the cotangent of passed numeric expression. SELECT COT(1);

    return: 0.64209261593433

    DEGREES() Returns numeric expression converted from radians todegrees.

    SELECT DEGREES(PI());

    return: 180.000000

    EXP() Returns the base of the natural logarithm (e) raised to

    the power of passed numeric expression.

    SELECT EXP(3);

    return: 20.085537FLOOR() Returns the largest integer value that is not greater

    than passed numeric expression.SELECT FLOOR(7.55);

    return: 7

    FORMAT() Returns a numeric expression rounded to a number ofdecimal places.

    SELECT FORMAT(423423234.65434453,2);

    return: 423,423,234.65

    GREATEST() Returns the largest value of the input expressions. SELECT GREATEST(33,99,34,55,67);

    return: 99

    INTERVAL() Takes multiple expressions exp1, exp2 and exp3 soon.. and returns 0 if exp1 is less than exp2, returns 1 ifexp1 is less than exp3 and so on.

    SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);

    return: 6

    LEAST() Returns the minimum-valued input when given two ormore.

    SELECT LEAST(3,5,1,8,33,99,34,55,67,43);

    return: 1

    LOG() Returns the natural logarithm of the passed numericexpression.

    SELECT LOG(45);

    return: 3.806662

    LOG(B,X) returns the logarithm of X for an arbitrary base B SELECT LOG(2,65536);

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    15/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 15 of 43

    return: 16.000000

    LOG10() Returns the base-10 logarithm of the passed numericexpression.

    SELECT LOG10(100);

    return: 2.000000

    MOD() Returns the remainder of one expression by diving byanother expression.

    SELECT MOD(29,3);

    return: 2

    OCT() Returns the string representation of the octal value ofthe passed numeric expression. Returns NULL ifpassed value is NULL.

    SELECT OCT(12);

    return: 14

    PI() Returns the value of pi SELECT PI();

    return: 3.141593

    POW()POWER()

    Returns the value of one expression raised to thepower of another expression

    SELECT POWER(3,3);

    return: 27

    RADIANS() Returns the value of passed expression convertedfrom degrees to radians.

    SELECT RADIANS(90);

    return: 1.570796

    ROUND() Returns numeric expression rounded to an integer.Can be used to round an expression to a number ofdecimal points

    SELECT ROUND(5.693893);

    return: 6

    ROUND() Returns numeric expression rounded to an integer.Can be used to round an expression to a number ofdecimal points

    ROUND(5.693893,2)

    return: 5.69

    SIGN() This function returns the sign of X (negative, zero, or

    positive) as .1, 0, or 1.

    SELECT SIGN(-4.65);

    return: -1

    SIN() Returns the sine of numeric expression given inradians.

    SELECT SIN(90);

    return: 0.893997

    SQRT() Returns the non-negative square root of numericexpression.

    SELECT SQRT(49);

    return: 7

    STD()STDDEV()

    Returns the standard deviation of the numericexpression.

    SELECT STD(PRICE) STD_DEVIATION FROM

    CARS;

    return:

    STD_DEVIATION

    +------------+

    7650.2146

    TAN() Returns the tangent of numeric expression expressedin radians.

    SELECT TAN(45);

    return: 1.619775

    TRUNCATE() Returns numeric exp1 truncated to exp2 decimalplaces. If exp2 is 0, then the result will have nodecimal point.

    SELECT TRUNCATE(7.536432,2);

    return: 7.53

    TEXT

    GROUP(Aggregate)

    MAX( ) This returns a selected column's highest value

    MIN( ) This returns a selected column's lowest value

    SUM( ) This returns the sum of a selected column

    AVG( ) This returns the average value of a selected column

    COUNT( ) This counts the number of rows in a selected column

    CONCAT CONCAT(col1,col2)

    SYSTEM INFOSHOW DATABASES; Shows all databases

    SHOW ENGINES; This returns a selected column's lowest value

    SHOW CHARACTER SET; This returns the sum of a selected column

    SHOW CREATE DATABASE ; This returns the average value of a selected column

    SHOW DATABASES; This counts the number of rows in a selected column

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    16/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 16 of 43

    PRIVILEGESUser Privileges

    ALTER Modify the structure or properties of a table

    ALTER ROUTINE Modify a stored routineCREATE Create new tables or databases

    CREATE ROUTINE Create routine

    CREATE TEMPORARY TABLE Create temporary table(s)

    CREATE VIEW Create a view

    DELETE Delete existing data from table (row or col)

    DROP Delete existing table

    EXECUTE Run a stored routine

    INDEX Create and delete indexes in tables

    INSERT Create new row (record) in existing table

    LOCK TABLES Global privilege. Prevent access during maintenance or update.

    REPLICATION CLIENT Show replication statusREPLICATION SLAVE Perform replication

    SELECT Read row(s) (records)

    SHOW DATABASE Global privilege. View available databases

    SHOW VIEW Use a view

    UPDATE Alter existing row or col data

    Admin Privileges

    CREATE USER Create new users

    DROP USER Delete a user

    FILE Import data from file(s) Global privilege that gives query rights.

    GRANT OPTION Create new users with same permission as current user

    PROCESS View current processes that are running

    RELOAD Global privilege. Reload grant tables, enact rules.

    REVOKE Remove specific privileges of a user

    SHUTDOWN Stop SQL server

    SUPER Terminate running processes

    OPERATOR ADMIN PRIVILEGES EXAMPLE

    GRANT

    GRANT , ON TO user;

    GRANT SELECT, INSERT, UPDATEON contactsTO john_doe;

    GRANT SELECT, INSERT, UPDATEON sales.*TO mary_doe;

    GRANT SELECT, INSERT, UPDATEON sales.*TO mary_doeIDENTIFIED BY password;

    PASSWORD(your password)

    SET PASSWORD = PASSWORD(newpassword) WHERE first_name='John' AND(last_name='Lennon' ORlast_name='Mellencamp');

    PASSWORD(user password)

    SET PASSWORD FOR user =PASSWORD(newpassword)

    SELECT fname, emailFROM contactsWHERE contact_id = 6;

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    17/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 17 of 43

    COMMANDSCommand Syntax Example

    AS(aliase)

    CONCAT(col1,col2) AS alias FROM tbl

    SELECT col AS col_aliase FROM tbl AS tbl_aliase

    CONCAT(lname,,,fnamecol2)AS fullname FROM contacts;

    CREATE

    CREATE TABLE ( INT IDENTITY (start, increment) NOTNULL, () NULL , () NULL);

    CREATE TABLE contacts (contact_id INT IDENTITY (1, 1) NOT NULL,first_name CHAR (30) NULL ,last_name CHAR (50) NULL ,email VARCHAR (75) NULL);

    COUNTSELECT COUNT(*) AS FROM ;

    SELECT COUNT(*) AS sales_totalFROM sales;

    SELECT company_col,COUNT(*) AS co_sales_col

    FROM sales_tblGROUP BY company_col;

    company_name company_sales---------------- -------------------------Amazon.com 478Sears 222CompUSA 512Dollar General Stores 6

    SELECT company_col,COUNT(*) AS co_sales_total_col

    FROM sales_tblGROUP BY company_colORDER BY company_col ASC;

    company_name company_sales---------------- -------------------------

    Amazon.com 478CompUSA 512Dollar General Stores 6Sears 222

    SELECT MAX(amount_col)FROM receipts_tblWHERE date_col = '01/01/2002'

    MAXimum sale from column "sale_total" in table "sales_log"for sales on 1/1/2002

    SELECT AVG(sales_col)FROM receipts_tableWHERE date_col = '01/01/2002';

    Get the average sale for a given day.

    SELECT COUNT(msg_col) AS count_colFROM msg_tblWHERE category = 'SQL';

    An example of using COUNT to get the number ofmessages posted to a discussion group:

    SELECT COUNT(DISTINCTjob_type_col)FROM jobs_tbl;

    This will give you the total number of unique job types inyour job group.

    DELETEDELETE FROM

    WHERE ;

    DELETE FROM contacts

    WHERE contact_id = 3;DISTINCT

    (No duplicates)SELECT DISTINCT

    FROM ;

    SELECT DISTINCTjob_type_colFROM jobs_tbl;

    Gives unique list of job types in your job group.

    INSERT

    new info orcopy table

    INSERT INTO (, , )VALUES (value, value, 'value');

    INSERT INTO (, , )SELECT col1, col2, col3 FROM other_tbl;

    INSERT INTO contacts (fname, lname, email)VALUES ('John', NULL, '[email protected]');

    INSERT INTO (, , )VALUES (value, value, 'value');

    INSERT INTO contacts (fname, lname, email)VALUES ('John', NULL, '[email protected]');

    LIKE(case insensitive

    or wildcards)

    SELECT , # or SELECT *FROM WHERE LIKE

    WHERE last_name LIKE '%camp%'or combinations

    WHERE first_name='John' ANDlast_name LIKE '%camp'

    ORDER BY

    ASC = ascendingDESC = descend

    SELECT *FROM ORDER BY ; ascending is default

    orORDER BY ;

    SELECT *

    FROM contactsORDER BY lname;

    or direction specificORDER BY lname DESC;or multiple columns

    ORDER BY last_name, first_name ASC;

    PASSWORD(your password)

    SET PASSWORD = PASSWORD(newpassword) WHERE first_name='John' AND(last_name='Lennon' ORlast_name='Mellencamp');

    PASSWORD(user password)

    SET PASSWORD FOR user =PASSWORD(newpassword)

    SELECT fname, emailFROM contactsWHERE contact_id = 6;

    SELECT

    SELECT * # select allor

    SELECT , # select specific col(s)FROM

    WHERE ;

    SELECT fname, emailFROM contactsWHERE contact_id = 6;

    UPDATE UPDATE UPDATE contacts

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    18/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 18 of 43

    SET = 'value'WHERE ;

    SET email = '[email protected]'WHERE contact_id = 6;

    WHERE(case sensitive)

    WHERE ;or

    WHERE LIKE ;

    WHERE first_name='John' AND(last_name='Lennon' ORlast_name='Mellencamp');

    ALTER SYNTAX EXAMPLE

    ADD COLUMNALTER TABLE tblADD COLUMN new_col col_type;

    ALTER TABLE contacsADD COLUMN ssn_num INT;

    CHANGECOLUMN

    ALTER TABLE tblCHANGE COLUMN old_col new_name new_type;

    INSERT INTO contacts (fname, lname, email)VALUES ('John', NULL, '[email protected]');

    DROPCOLUMNALTER TABLE tblDROP COLUMN col;

    DELETE FROM contactsWHERE contact_id = 3;

    ADD INDEXALTER TABLE tblADD INDEX index_name col;

    UPDATE contactsSET email = '[email protected]'WHERE contact_id = 6;

    DROP INDEXALTER TABLE tblDROP INDEX index_name;

    SELECT fname, emailFROM contactsWHERE contact_id = 6;

    RENAME ASALTER TABLE tblRENAME AS new_tbl_name;

    WHERE first_name='John' AND(last_name='Lennon' ORlast_name='Mellencamp');

    ENGINESName DESCRIPTION

    MyISAMThe default MySQL storage engine and the one that is used the most in Web, data warehousing, and otherapplication environments. MyISAM is supported in all MySQL configurations, and is the default storage engineunless you have configured MySQL to use a different one by default.

    Memory(heap)

    Stores all data in RAM for extremely fast access in environments that require quick lookups of reference and otherlike data.

    MergeAllows a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them asone object. Good for VLDB environments such as data warehousing.

    InnoDBUsed for transaction processing applications, and sports a number of features including ACID transaction supportand foreign keys.

    ArchiveProvides the perfect solution for storing and retrieving large amounts of seldom-referenced historical, archived, or

    security audit information.

    FederatedOffers the ability to link separate MySQL servers to create one logical database from many physical servers. Verygood for distributed or data mart environments.

    NDBCLUSTER(NDB)

    This clustered database engine is particularly suited for applications that require the highest possible degree ofuptime and availability.

    CSVThe CSV storage engine stores data in text files using comma-separated values format. You can use the CSVengine to easily exchange data between other software and applications that can import and export in CSVformat.

    BlackholeThe Blackhole storage engine accepts but does not store data. Retrievals always return an empty set. Thefunctionality can be used in distributed database design where data is automatically replicated, but not storedlocally.

    ExampleTables can be created, but no data can be stored or retrieved. This engine serves as an example in MySQLsource code. It illustrates how to begin writing new storage engines but does nothing.

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    19/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 19 of 43

    USER OPERATIONS

    Update database permissions / privileges.

    flush privileges;

    Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.

    # mysql -u root -p

    use mysql;

    INSERT INTO user (Host,User,Password)

    VALUES('%','username',PASSWORD('password'));

    flush privileges;

    Change a users password FROM unix shell.

    mysql/path/mysqladmin -u username -h hostname.blah.org -p password 'new-

    password'

    Change a users password FROM MySQL prompt. Login as root. Set the password. Update privs.

    # mysql -u root -p

    SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');

    flush privileges;

    Recover a MySQL root password.

    Stop the MySQL server process.

    Start again with no grant TABLEs.

    Login to MySQL as root.

    Set new password.

    Exit MySQL and restart MySQL server.

    # /etc/init.d/mysql stop

    # mysqld_safe --skip-grant-TABLEs mysql -u root

    use mysql;

    update user set password=PASSWORD("newrootpassword") WHERE User='root';

    flush privileges;

    quit

    # /etc/init.d/mysql stop

    # /etc/init.d/mysql start

    Set a root password if there is no root password.

    # mysqladmin -u root password newpassword

    Update a root password.

    # mysqladmin -u root -p oldpassword newpassword

    Allow the user "bob" to connect to the server FROM localhost using the password "passwd".

    Login as root. Switch to the MySQL db. Give privileges. Update privileges.

    # mysql -u root -p

    use mysql;

    grant usage on *.* to bob@localhost identified by 'passwd';

    flush privileges;

    Give user privileges for a db.

    Login as root.

    Switch to the MySQL db.

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    20/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 20 of 43

    Grant privileges. Update privs.

    # mysql -u root -p

    use mysql;

    INSERT INTO db

    (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,DROP_p

    riv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');

    flush privileges;

    or

    grant all privileges on databasename.* to username@localhost;

    flush privileges;

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    21/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 21 of 43

    DATABASE OPERATIONS

    Create a database.

    mysql_query("CREATE DATABASE dbName",$db);

    To delete a db.

    mysql_query("DROP DATABASE dbName",$db);

    List all databases on the sql server.

    mysql_query("SHOW DATABASES",$db);;

    Switch to or select a database.

    USE dbName;

    BACKUP all databases. Backup file is sql commands to recreate all db's.

    mysql/path/mysqldump -u username p password --opt > /path/all_db.sql

    or

    mysql/path/mysqldump -u username p password all-databases > /path/all_db.sql

    BACKUP one database.

    mysql/path/mysqldump -u username p password --databases dbName >

    /path/dbName.sql

    Restore database (or database TABLE) FROM backup.

    mysql/path/mysql -u username p password databasename < /tmp/databasename.sql

    Batch or script.

    mysql/path/mysql -u username p password < /path/script.txt

    # use -t for nice TABLE layout and -vvv for command echoing.

    mysql/path/mysql > /path/script.txt

    Load CSV COMMA DELIMITED file into a TABLE.

    LOAD DATA LOCAL INFILE '/path/filename.csv'

    replace INTO TABLE t1

    FIELDS TERMINATED BY ','

    LINES TERMINATED BY '\n' (field1,field2,field3);

    Load TAB DELIMITED file into a TABLE.

    LOAD DATA LOCAL INFILE '/path/filename.tab' into table dbNAME.t1 fields

    terminated by 't' enclosed by '"' lines terminated by 'rn';

    # rn mean new lines. r means carriage return. n means new line.

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    22/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 22 of 43

    TABLE OPERATIONS

    Show all TABLES in current db.

    SHOW TABLES;

    Show database column format.

    DESCRIBE t1;

    DELETE a TABLE.

    DROP TABLE t1;

    TRUNCATE a TABLE. (deletes TABLE, then recreate with same fields, the reset the AUTO INCREMENT counter to '0')

    DROP TABLE t1;

    Clear and reset a table. Deletes, re-creates, set auto-inc to 0

    truncate table t1;

    SHOW all data in a TABLE.SELECT * FROM t1;

    UPDATE an existing row in TABLE.

    UPDATE t1 SET c1 = 'something' WHERE c2 = 'somewhere';

    Delete a row(s) FROM a TABLE.

    DELETE FROM t1 WHERE c1 = 'whatever';

    Rename TABLE.

    ALTER TABLE IF EXISTS `my_orig_table` RENAME `my_new_name`;

    Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.

    SHOW COLUMNS FROM t1;

    Dump a TABLE FROM a database.

    mysql/path/mysqldump -c -u username -ppassword databasename TABLEname >

    /tmp/databasename.TABLEname.sql

    Copy table structure

    CREATE TABLE t1 SELECT * FROM t2

    Create TABLE Example 1.

    CREATE TABLE t1 (id INT PRIMARY KEY,

    c1 VARCHAR(35),

    datestamp DATE,

    timestamp time

    ); # end of table

    Create TABLE Example 2.

    create TABLE t1 (

    id int(50) NOT NULL AUTO_INCREMENT PRIMARY KEY,

    c1 varchar(35),

    c2 varchar(50) DEFAULT 'hello')

    ; # end of table

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    23/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 23 of 43

    COLUMN OPERATIONS

    Delete a COLUMN.

    ALTER TABLE t1 DROP COLUMN c1;

    Add a new COLUMN to TABLE.

    ALTER TABLE t1 ADD COLUMN newName varchar(20);

    Rename COLUMN name.

    ALTER TABLE t1 change oldName newName varchar(50);

    Make a UNIQUE COLUMN so you get no dupes.

    ALTER TABLE t1 ADD UNIQUE c1;

    Make a COLUMN bigger.

    ALTER TABLE t1 MODIFY c1 VARCHAR(3);

    Delete UNIQUE FROM TABLE.

    ALTER TABLE t1 DROP INDEX c1;

    Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.

    SHOW COLUMNS FROM t1;

    Selecting column.

    SELECT c1 FROM t1;

    SELECT c1, c2 FROM t1 WHERE c2 = "smith" ORDER BY c2;

    Sorting.SELECT c1, c2 FROM t1 ORDER BY c2;

    SELECT c1, c2 FROM t1 ORDER BY c2 DESC; # reverse

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    24/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 24 of 43

    ROW OPERATIONS (SELECT)

    DELETE row.

    DELETE from t1 where c1 = 'whatever';

    UPDATE row.

    UPDATE t1 SET c1=value, c2=value2,... WHERE c3=value

    SHOW selected rows with the value "whatever".

    SELECT * FROM t1 WHERE c1 = "whatever";

    SHOW rows containing the name "Bob" AND the ph number '123-4567'.

    SELECT * FROM t1 WHERE c1 = "Bob" AND c2 = '123-4567';

    SHOW rows not containing "Bob" AND the ph number '123-4567', order ph_number.

    SELECT * FROM t1 WHERE c1 != "Bob" AND c2 = '123-4567' order by c2;

    SHOW all rows starting with the letters 'bob' AND the ph number '123-4567'.SELECT * FROM t1 WHERE c1 LIKE "Bob%" AND c2 = '123-4567';

    SHOW all rows starting with the letters 'bob' AND the ph number '123-4567' LIMIT to rows 1 through 5.

    SELECT * FROM t1 WHERE c1 LIKE "Bob%" AND c2 = '123-4567' LIMIT 1,5;

    Use regex to find rows.

    Use "REGEXP BINARY" to force case-sensitivity.

    This finds any record beginning with a.

    SELECT * FROM t1 WHERE REC RLIKE "^a";

    SELECT * FROM t1 WHERE REC RLIKE "text%";

    SHOW UNIQUE rows.

    SELECT DISTINCT c1 FROM t1;

    SHOW rows sorted in an ascending (asc) or descending (desc).

    SELECT c1, c2 FROM t1 ORDER BY c2 DESC;

    INSERT one or more rows from one table to another table.

    INSERT INTO t1(c1, c2) SELECT (b1, b2) from t2 where 1;

    Where conditions

    The WHERE exp is used to modify a DELETE, SELECT, or UPDATE SQL query.

    Syntaxt1, t2 are TABLE namesc1, c2 are COLUMN or FIELD names

    $result is a resource OBJECT$rows is an array of records

    $rowis a single RECORD$dbis a database object

    Simple statement

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    25/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 25 of 43

    SELECT * FROMt1

    Advanced statement using WHERE

    SELECT ALIASE

    FROM WHEREexpAND|ORexpAND|ORexp...

    ORDER BY

    This list shows the format you can use when writing a WHERE exp (expression). The where exp can be oneof the following:

    column = value equal

    column != value not equal

    column > value more thancolumn >= value more than or equal to

    column < value less than

    column

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    26/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 26 of 43

    COUNT, SUM, MAX

    Return number of rows.

    $result = mysql_query("SELECT * FROM tablename");

    $num_rows = mysql_num_rows($result);

    or

    $num_rows = mysqli_num_rows($result);

    Distinct counts.

    SELECT c1, COUNT(*) FROM t1 GROUP BY c1; # distinct count

    or

    SELECT count(distinct c1) as distinct_items FROM t1);

    Sum COLUMN.

    SELECT SUM(c1) FROM t1;

    MAXIMUM value.

    SELECT MAX(c1) AS label FROM t1;

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    27/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 27 of 43

    PHP & REGEX SEARCHS

    Regular PHP expressions use patterns to test whether the input users submit when using online forms are inthe correct format. This table shows characters you can use in patterns.

    Character Meaning Example Match Not a Match

    ^ Beginning of line ^c cat my cat

    $ End of line c$ tic stick

    . Any single character .. me, go a

    ? Preceding item is optional mea?n mean, men moan

    ( ) Groups literal characters m(ea)n mean men,mn

    [ ] Any character in set abc[1-3] abc1,abc2 abc4

    [! ] Any character not in set m[!ea]n min, mon men, man

    + One or more door[1-3]+ door111, door131 door, door55

    * Zero or more door[1-3]* door, door311 door4, door445

    { , } Range of repetitions a{2,5} aa,aaaaa a, xx3

    \ Escapes character m\*n m*n men, mean

    ( | | ) Alternate strings (Tom|Tommy) Tom, Tommy Thomas, To

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    28/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 28 of 43

    JOIN UNION GROUP

    JOIN or INNER JOIN: Return rows when there is at least one match in both tables

    LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table

    RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table. A

    right join is identical to a left join if the position of the tables is swapped.FULL JOIN: Merges the tables (including unmatched rows) as if a LEFT and RIGHT JOIN where

    used at the same time.

    UNION: Adds returned rows of one table to the returned rows of another table.

    GROUP: Adds returned rows of one table to the returned rows of another table.

    Test db setup: To demonstrate joins consider a database named test with two tables with acustomer ID in common, when with credit limits, and the other with phone numbers.The each have customer id rows that are unique and two rows that are in common.We delibertly have different column names for the ID to show that the key field does

    not have to be named the same.

    Table t1 Table t2cust_id credit cust_num phone

    1 50 3 123-45672 75 4 234-5678

    3 100 5 345-67894 150 6 456-7890

    They can be created by using the following sql statements:

    DROP DATABASE IF EXISTS `test` ;

    CREATE DATABASE `test` ;

    CREATE TABLE `test`.`t1` (

    `cust_id` INT( 4 ) NOT NULL,

    `credit` DECIMAL( 6,2 ) NOT NULL ,

    PRIMARY KEY ( `cust_id` )

    ) ENGINE = InnoDB;

    INSERT INTO `test`.`t1` (`cust_id` ,`credit` )

    VALUES

    ('1', '50')

    , ('2', '75')

    , ('3', '100')

    , ('4', '150')

    ;

    CREATE TABLE `test`.`t2` (

    `cust_num` INT( 4 ) NOT NULL ,

    `phone` VARCHAR( 15 ) NOT NULL ,

    PRIMARY KEY ( `cust_num` )

    ) ENGINE = InnoDB;

    INSERT INTO `test`.`t2` (`cust_num` ,`phone` )

    VALUES

    ('3', '123-4567')

    , ('4', '234-5678')

    , ('5', '345-6789')

    , ('6', '456-7890')

    ;

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    29/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 29 of 43

    JOIN(default), INNER JOIN, and WHERE: Return rows when there is a match in both tables. Note, that aWHERE is often used as a shortcut to this type of JOIN. AnINNER JOIN is the same as a JOIN.

    SELECT *

    FROM t1, t2

    WHERE t1.cust_id = t2.cust_num

    or

    SELECT *

    FROM t1

    JOIN t2

    WHERE t1.cust_id = t2.cust_num

    or

    SELECT *

    FROM t1INNER JOIN t2 ON t1.cust_id = t2.cust_num

    Table t1 Table t2

    cust_id credit cust_num phone1 50 3 123-45672 75 4 234-5678

    3 100 5 345-67894 150 6 456-7890

    Result:

    cust_id credit cust_num phone

    3 100.00 3 123-4567

    4 150.00 4 234-5678

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    30/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 30 of 43

    LEFT JOIN: Return all rows from the left table, even when no match is found in the right table.

    The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility anddoesn't add any extra capabilities.

    SELECT *

    FROM t1

    LEFT JOIN t2 ON t1.cust_id = t2.cust_num

    Table t1 Table t2cust_id credit cust_num phone

    1 50 3 123-45672 75 4 234-56783 100 5 345-67894 150 6 456-7890

    Result:

    cust_id credit cust_num phone

    1 50.00 NULL NULL

    2 75.00 NULL NULL

    3 100.00 3 123-4567

    4 150.00 4 234-5678

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    31/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 31 of 43

    RIGHT JOIN: Return all rows from the right table, even when no match is found in the left table. Note that aRIGHT JOIN can be duplicated by swapping table positions and using a LEFT JOIN.

    The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility anddoesn't add any extra capabilities.

    SELECT *

    FROM t1

    RIGHT JOIN t2 ON t1.cust_id = t2.cust_num

    or

    SELECT *

    FROM t2

    LEFT JOIN t1 ON t1.cust_id = t2.cust_num

    Table t1 Table t2

    cust_id credit cust_num phone1 50 3 123-45672 75 4 234-5678

    3 100 5 345-67894 150 6 456-7890

    Result:

    cust_id credit cust_num phone

    3 100.00 3 123-4567

    4 150.00 4 234-5678

    NULL NULL 5 345-6789NULL NULL 6 456-7890

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    32/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 32 of 43

    FULL JOIN, FULL OUTER JOIN, CROSS JOIN:This JOIN combines both tables (as if a LEFT and RIGHT JOIN whereused together). MySql does not provide a FULL JOIN because it is rarelyneeded. You can create one by using a union statement.

    A STRAIGHT JOIN is a full JOIN except that the JOIN occurs in the

    order given in the command line. Otherwise, the database engine is freeto display things in the order in which is most convenient.

    SELECT t1.*, t2.* FROM t1,t2 WHERE t1.cust_id = t2.cust_num

    or

    SELECT * FROM t1

    LEFT JOIN t2

    ON t1.cust_id = t2.cust_num

    UNION

    SELECT * FROM t1

    RIGHT JOIN t2

    ON t1.cust_id = t2.cust_num

    Table t1 Table t2cust_id credit cust_num phone

    1 50 3 123-45672 75 4 234-5678

    3 100 5 345-67894 150 6 456-7890

    Result:

    cust_id credit cust_num phone

    1 50.00 NULL NULL2 75.00 NULL NULL

    3 100.00 3 123-4567

    4 150.00 4 234-5678

    NULL NULL 5 345-6789

    NULL NULL 6 456-7890

    To do this with three tables

    -- three tables t1, t2, t3:

    SELECT * FROM t1

    LEFT JOIN t2 ON t1.id = t2.id

    LEFT JOIN t3 ON t2.id = t3.id

    UNION

    SELECT * FROM t1

    RIGHT JOIN t2 ON t1.id = t2.id

    LEFT JOIN t3 ON t2.id = t3.id

    UNION

    SELECT * FROM t1

    RIGHT JOIN t2 ON t1.id = t2.id

    RIGHT JOIN t3 ON t2.id = t3.id

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    33/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 33 of 43

    UNION: returns a table with column positions merged to the first tables field names.

    SELECT * FROM t1

    UNION

    SELECT * FROM t2

    Table t1 Table t2

    cust_id credit cust_num phone

    1 50 3 123-45672 75 4 234-5678

    3 100 5 345-67894 150 6 456-7890

    Result:

    cust_id credit

    1 50.00

    2 75.00

    3 100.00

    4 150.00

    3 123-4567

    4 234-5678

    5 345-6789

    6 456-7890

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    34/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 34 of 43

    GROUP: returns a table with unique row data.

    Suppose we would like to know what types of credit we offer our customers.

    SELECT credit FROM t1 GROUP BY credit

    Table t1

    cust_id credit1 752 75

    3 100

    4 1005 150

    Result:

    credit

    75.00

    100.00

    150.00

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    35/43

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    36/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 36 of 43

    PERIOD_ADD() - adds an interval (in months) to a date and returns a new date

    Date Datatypes

    There are 5 MySQL date datatypes these are:

    Datatype Format Info

    DATETIME YYYY-MM-DD HH:MM:SS This stores both date and time.

    DATE YYYY-MM-DD This only stores the date

    TIMESTAMP(length) Varies See Below

    TIME HH:MM:SS This stores only the time

    YEAR YYYY Stores only the year

    The timestamp datatype is somewhat different as it stores the time that a row was last changed. The formatalso varies according to the length. For example to store the same information as DATETIME, you would specify

    a length of 14 whereas to store the DATE you would specify a length of 8.

    Timestamp Definition Format

    TIMESTAMP(2) YY

    TIMESTAMP(4) YYYY

    TIMESTAMP(6) YYMMDD

    TIMESTAMP(8) YYYYMMDD

    TIMESTAMP(10) YYMMDDHHMM

    TIMESTAMP(12) YYMMDDHHMMSS

    TIMESTAMP(14) YYYYMMDDHHMMSS

    In the 'cds' table we have used the DATE for the 'bought' field.mysql> SELECT cds.title, cds.bought

    -> FROM cds;

    +------------------------------+------------+

    | title | bought |

    +------------------------------+------------+

    | A Funk Odyssey | 2001-10-10 |

    | Now 49 | 2001-10-15 |

    | Eurovision Song contest 2001 | 2000-09-08 |

    | Abbas Greatest Hits | 2000-11-05 |

    | Space Cowboy | 2001-10-10 |

    | Sign of the times | 1987-11-07 |

    | The White Album | 1994-07-20 |

    | The Hits | 1993-10-07 |

    | westlife | 2000-06-09 |

    +------------------------------+------------+

    9 rows in set (0.02 sec)

    So to begin with let's look at how we can manipulate these dates using MySQL's date functions.

    DATE_FORMAT()

    This function allows the developer to format the date anyway that they wish by specifying a sequence of formatstrings. A string is composed of the percentage symbol '%' followed by a letter that signifies how you wish todisplay part of the date. These are some of the more common strings to use:

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    37/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 37 of 43

    String Displays Example

    %d The numeric day of the month 01....10....17....24 etc

    %D The day of the month with a suffix 1st, 2nd, 3rd.... etc

    %m The numeric month 01....04....08....11 etc

    %M The Month name January....April....August etc

    %b The Abbreviated Month Name Jan....Apr....Aug....Nov etc

    %y Two digit year 98, 99, 00, 01, 02, 03 etc

    %Y Four digit year 1998, 2000, 2002, 2003 etc

    %W Weekday name Monday.... Wednesday....Friday etc

    %a Abbreviated Weekday name Mon....Wed....Fri etc

    %H Hour (24 hour clock) 07....11....16....23 etc

    %h Hour (12 hour clock) 07....11....04....11 etc

    %p AM or PM AM....PM

    %i Minutes 01....16....36....49 etc

    %s Seconds 01....16....36....49 etc

    There are more, but that should be enough for now. There are a couple of things to note. Upper and Lowercase

    letters in the string make a difference and also that when arranging these strings into a sequence you canintersperse 'normal' characters. For example:

    The sequence '%d/%m/%y', with forward slashes separating the strings, would be displayed as 01/06/03.

    The next stage is to use the function DATE_FORMAT() to convert a stored time to a format we want.

    Syntax:

    DATE_FORMAT(date, sequence)

    Thus to change the format of the cds.bought field to DD-MM-YYYY we specify the field as the date and thesequence as '%d-%m-%Y'.

    DATE_FORMAT(cds.bought, '%d-%m-%Y')

    This function is then incorporated into our SQL statement in place of the exiting cds.bought field.

    mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%d-%m-%Y') FROM cds;

    +------------------------------+-------------------------------------+

    | title | DATE_FORMAT(cds.bought, '%d-%m-%Y') |

    +------------------------------+-------------------------------------+

    | A Funk Odyssey | 10-10-2001 |

    | Now 49 | 15-10-2001 |

    | Eurovision Song contest 2001 | 08-09-2000 |

    | Abbas Greatest Hits | 05-11-2000 |

    | Space Cowboy | 10-10-2001 |

    | Sign of the times | 07-11-1987 |

    | The White Album | 20-07-1994 |

    | The Hits | 07-10-1993 |

    | westlife | 09-06-2000 |

    +------------------------------+-------------------------------------+

    9 rows in set (0.00 sec)

    Dates can also be formatted in 'plain english'.mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%W the %D of %M %Y')

    -> FROM cds;

    +------------------------------+-----------------------------------------------+

    | title | DATE_FORMAT(cds.bought, '%W the %D of %M %Y') |

    +------------------------------+-----------------------------------------------+

    | A Funk Odyssey | Wednesday the 10th of October 2001 |

    | Now 49 | Monday the 15th of October 2001 |

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    38/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 38 of 43

    | Eurovision Song contest 2001 | Friday the 8th of September 2000 |

    | Abbas Greatest Hits | Sunday the 5th of November 2000 |

    | Space Cowboy | Wednesday the 10th of October 2001 |

    | Sign of the times | Saturday the 7th of November 1987 |

    | The White Album | Wednesday the 20th of July 1994 |

    | The Hits | Thursday the 7th of October 1993 |

    | westlife | Friday the 9th of June 2000 |

    +------------------------------+-----------------------------------------------+

    9 rows in set (0.01 sec)

    Note: DATE_FORMAT() only works with datatypes that include the date. This means DATE, DATETIME andTIMESTAMP. There is a similar function called TIME_FORMAT() that works with TIME as well as DATETIME andTIMESTAMP.

    Extraction Functions

    As well as using DATE_FORMAT() there are other functions that allow you to extract specific information about adate (year, month, day etc). These include:

    Function Displays Example

    DAYOFMONTH(date) The numeric day of the month 01....10....17....24 etc

    DAYNAME(date) The Name of the day Monday.... Wednesday....Friday etc

    MONTH(date) The numeric month 01....04....08....11 etc

    MONTHNAME(date) The Month name January....April....August etc

    YEAR(date) Four digit year 1998, 2000, 2002, 2003 etc

    HOUR(time) Hour (24 hour clock) 07....11....16....23 etc

    MINUTE(time) Minutes 01....16....36....49 etc

    SECOND(time) Seconds 01....16....36....49 etc

    DAYOFYEAR(date) Numeric day of the year 1.....366

    To give an example of one of these you can use DAYNAME() to work out which day you were born on. To do this

    you can specify the date directly to the function without referring to any tables or field. So for my birthday (20thJuly 1973):

    mysql> SELECT DAYNAME('1973-07-20');

    +-----------------------+

    | DAYNAME('1973-07-20') |

    +-----------------------+

    | Friday |

    +-----------------------+

    1 row in set (0.00 sec)

    Or you could even SELECT two or three date items.mysql> SELECT DAYNAME('1973-07-20'), MONTHNAME('1973-07-20'), YEAR('1973-07-20');

    +-----------------------+-------------------------+--------------------+

    | DAYNAME('1973-07-20') | MONTHNAME('1973-07-20') | YEAR('1973-07-20') |

    +-----------------------+-------------------------+--------------------+

    | Friday | July | 1973 |

    +-----------------------+-------------------------+--------------------+

    1 row in set (0.02 sec)

    Getting the Current Date and Time

    There are three functions that you can use to get the current date and time. NOW() - which gets both date andtime, CURDATE() which works with only the date and CURTIME() for the time.

    mysql> SELECT NOW(), CURTIME(), CURDATE();

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    39/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 39 of 43

    +---------------------+-----------+------------+

    | NOW() | CURTIME() | CURDATE() |

    +---------------------+-----------+------------+

    | 2003-06-02 19:44:51 | 19:44:51 | 2003-06-02 |

    +---------------------+-----------+------------+

    1 row in set (0.01 sec)

    Changing Date Values

    There are two functions that allow you to add and subtract time to a date. These are DATE_ADD() andDATE_SUB().

    Syntax:

    DATE_ADD(date,INTERVAL expr type)

    DATE_SUB(date,INTERVAL expr type)

    The date - is a standard DATE or DATETIME value, next come the command INTERVAL followed by the time

    period (expr) and finally what type period it is (Month, Day, Year etc). Therefore to work out the date 60 daysin the future:

    mysql> SELECT DATE_ADD(CURDATE(), INTERVAL 60 DAY);

    +--------------------------------------+

    | DATE_ADD(CURDATE(), INTERVAL 60 DAY) |

    +--------------------------------------+

    | 2003-08-01 |

    +--------------------------------------+

    1 row in set (0.00 sec)

    Or 6 months in the past:

    mysql> SELECT DATE_SUB(CURDATE(), INTERVAL 6 MONTH);

    +---------------------------------------+

    | DATE_SUB(CURDATE(), INTERVAL 6 MONTH) |

    +---------------------------------------+

    | 2002-12-02 |

    +---------------------------------------+

    1 row in set (0.00 sec)

    We can also format this result as well using DATE_FORMAT() and using an alias to

    tidy up the title:

    mysql> SELECT

    -> DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), '%W the %D of %M %Y')-> AS 'Six Months Ago';

    +---------------------------------+

    | Six Months Ago |

    +---------------------------------+

    | Monday the 2nd of December 2002 |

    +---------------------------------+

    1 row in set (0.01 sec)

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    40/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 40 of 43

    USING PHP STATEMENTS

    Here is a list of the most common PHP statements that are used with MySql programs:

    Common single statements

    array ( "key" => "value", ... );die ("message");

    echo string and or $var;

    echo string and or . $var;

    header("Location: URL");

    number_format(number,decimals);

    session_start();

    session_destroy();

    unset();extract($array);

    for

    for(startingval; endingval;incremnt) {

    code block...}

    foreach

    foreach($array as $key => $value) {

    code block...

    }

    function

    functionfname(value,value,...) {

    code block...

    }

    if, ifelse, else

    if (condition) {

    code block...

    }elseif (condition) {

    code block...

    }else{

    code block...

    }

    while

    while (condition) {

    code block...

    }

    switch

    switchvar {

    casevalue1

    statements;

    break;

    casevalue2

    statements;

    break;

    ...

    }

    do

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    41/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 41 of 43

    do {

    code block...

    }

    while (condition);

    MYSQL FUNCTIONS

    mysql_affected_rows .............. Get number of affected rows in previous MySQL operation mysql_client_encoding ............ Returns the name of the character set mysql_close .......................... Close MySQL connection mysql_connect ...................... Open a connection to a MySQL Server mysql_create_db ................... Create a MySQL database mysql_data_seek ................... Move internal result pointer mysql_db_name .................... Get result data mysql_db_query .................... Send a MySQL query mysql_drop_db ..................... Drop (delete) a MySQL database mysql_errno ......................... Returns numerical value of previous MySQL error message

    mysql_error .......................... Returns text error message from previous MySQL operation mysql_escape_string .............. Escapes a string for use in a mysql_query mysql_fetch_array ................. Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc ................. Fetch a result row as an associative array mysql_fetch_field .................. Get column information from a result and return as an object mysql_fetch_lengths .............. Get the length of each output in a result mysql_fetch_object ................ Fetch a result row as an object mysql_fetch_row ................... Get a result row as an enumerated array mysql_field_flags ................... Get the flags associated with the specified field in a result mysql_field_len ..................... Returns the length of the specified field mysql_field_name .................. Get the name of the specified field in a result mysql_field_seek ................... Set result pointer to a specified field offset mysql_field_table ................... Get name of the table the specified field is in mysql_field_type ................... Get the type of the specified field in a result

    mysql_free_result .................. Free result memory mysql_get_client_info ............. Get MySQL client info mysql_get_host_info .............. Get MySQL host info mysql_get_proto_info ............. Get MySQL protocol info mysql_get_server_info ........... Get MySQL server info mysql_info ............................ Get information about the most recent query mysql_insert_id ..................... Get the ID generated in the last query mysql_list_dbs ...................... List databases available on a MySQL server mysql_list_fields .................... List MySQL table fields mysql_list_processes .............. List MySQL processes mysql_list_tables ................... List tables in a MySQL database mysql_num_fields .................. Get number of fields in result mysql_num_rows ................... Get number of rows in result mysql_pconnect .................... Open a persistent connection to a MySQL server mysql_ping ........................... Ping a server connection or reconnect if there is no connection mysql_query ......................... Send a MySQL query mysql_real_escape_string ....... Escapes special characters in a string for use in an SQL statement mysql_result ......................... Get result data mysql_select_db .................... Select a MySQL database mysql_set_charset ................. Sets the client character set mysql_stat ........................... Get current system status mysql_tablename .................. Get table name of field mysql_thread_id .................... Return the current thread ID mysql_unbuffered_query ......... Send SQL query to MySQL w/o fetching or buffering the result rows.

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    42/43

    MySql Reference by Jan Zumwalt NeatInfo.com February, 06, 2012Pg - 42 of 43

  • 8/3/2019 MYSQL & PHP Referance - Jan Zumwalt

    43/43

    Notes: _______________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ____________________________________________________________________________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ____________________________________________________________________________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ____________________________________________________________________________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________

    ______________________________________________________________