Jump to: navigation, search

PHP MySQL Insert, Delete, Update, and Select Statements

From w3cyberlearnings

Contents

Require

  • PHP, MySQL, Apache Web Server, Linux OS, and Eclipse or Netbean IDE
  • Understand basic PHP, HTML, and MySQL

PHP Connect to MySQL

  • Connect to the database required: user-name, password, database-name, and host name.
$host = "HOST NAME";
$username = "USER NAME";
$password = "PASSWORD ";

Connect to MySQL Database (Connect.php)

  • Display A connection to the MySQL could not be established! for unsuccessful connect to the database.
  • Dispaly Connect to MySQL is successful! for successful connect to the database.
<?php
  // connect to mysql parameters
  $host ='localhost';
  $username = 'username';
  $password= 'userpassowrd';

  // connect to mysql server
  $connection= mysql_connect ($host, $username, $password)
          or die("Unable to connect to the MySQL Server!");

  // check connect
  if (!$connection) {
     die ("A connection to the MySQL could not be established!");
  }
  else {
      echo "Connect to MySQL is successful!";
  }
  mysql_close($connection);
?>

Create Database

  • Create MySQL database name called: school200
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// query to create the school database
$create_database = "CREATE DATABASE IF NOT EXISTS school200";

// call this function to create the database
if (!mysql_query($create_database, $connection)) {
    echo "Can't create database: " . mysql_error($connection);
} else {
    echo "You have successfully created the database name school200";
}

// close connection
mysql_close($connection);
?>

PHP Delete Database

  • How to delete a database..
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

$deldatabase = "DROP DATABASE school200";

if (!mysql_query($deldatabase, $connection)) {
    echo "Can't delete database: " . mysql_error($connection);
} else {
    echo "You have successfully deleted database name school200";
}

// close connection
mysql_close($connection);
?>

PHP Create Table

  • Create a database table: student
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// student table
$create_table = 
                'CREATE TABLE IF NOT EXISTS student  (
                        student_id INT NOT NULL AUTO_INCREMENT,
                        first_name VARCHAR(30) NOT NULL,
                        last_name VARCHAR(30) NOT NULL,
                        PRIMARY KEY(student_id)
                  ) ENGINE=InnoDB';
// call this function to create the table
if (!mysql_query($create_table, $connection)) {
    echo "Can't create table: " . mysql_error($connection) . "<br/>";
} else {
    echo "You have successfully create student table <br/>";
}

// close connection
mysql_close($connection);
?>

PHP Delete Table

  • Delete a table will delete all the records in the table.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");


// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// student table
$delete_table = 'DROP TABLE IF EXISTS student';

// call this function to delete table
if (!mysql_query($delete_table, $connection)) {
    echo "Can't delete table: " . mysql_error($connection);
} else {
    echo "You have successfully delete student table";
}
// close connection
mysql_close($connection);
?>

PHP Insert Record

  • Insert record to the student table
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// insert to the student table query
$insert_query = '
                    INSERT INTO student (first_name, last_name)
                    VALUES
                    ("Johny","Zhar"),
                    ("Jacob","Milli"),
                    ("Isabella","Catous"),
                    ("Michael","Vieva"),
                    ("Emma","lee")
                ';
// insert to student table

if (!mysql_query($insert_query, $connection)) {
    echo "Can't insert student record : " . mysql_error($connection);
} else {
    echo "You have successfully insert student record into student table";
}

// close connection
mysql_close($connection);
?>

PHP Insert From Array

  • Insert records from array
  • First loop through the array, and do the insert
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// student array
$student_record = array(
    array("Peeou", "Zhou"),
    array("Isabel", "Peom"),
    array("Sophal", "Tang"),
    array("Chong", "Mok"),
    array("Ebo", "Kaun"));

for ($i = 0; $i < count($student_record); $i++) {
    // build a sql statement for insert
    $insert_sql = sprintf("INSERT INTO student (first_name, last_name) VALUES(\"%s\",\"%s\")",
                    $student_record[$i][0], $student_record[$i][1]);
    // insert to the student table
    mysql_query($insert_sql, $connection) or die(mysql_error($connection));
    echo "id: " . mysql_insert_id() ;
}

// close connection
mysql_close($connection);
?>

PHP Insert From File using LOAD DATA LOCAL INFILE

student.txt File Content

  • This is the file content to be inserted into the table
  • Separate first name and last with -.
  • Separate record with :.
lee-salina:so-pheank:lee-lyekwan:otam-kiloma

PHP program to insert file to the table

<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// insert to the student table query
$insert_query = "LOAD DATA LOCAL INFILE 'student.txt' 
                INTO table student
                FIELDS TERMINATED BY '-'
                LINES TERMINATED BY ':'
                (last_name,first_name)
                ";

if (!mysql_query($insert_query, $connection)) {
    echo "Can't insert student record : " . mysql_error($connection);
} else {
    echo "You have successfully insert student record into student table";
}
?>

PHP Update Record

<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$update_query = 'UPDATE student SET first_name="lili", last_name="lee" WHERE student_id IN (1,2,20)';

if (!mysql_query($update_query, $connection)) {
    echo "Can't update student table: " . mysql_error($connection);
} else {
    echo "You have successfully update the student table";
}

// close connection
mysql_close($connection);
?>

PHP Delete Record

  • Delete Record From Student Table
  • When you want to delete a record, you can delete it by using a DELETE STATEMENT.
  • You have to specify a specific row that you want to delete by using the row unique ID.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// Delete statement
$delete_query = 'DELETE FROM student WHERE student_id=5';

if (!mysql_query($delete_query, $connection)) {
    echo "Can't delete from student table: " . mysql_error($connection);
} else {
    echo "You have successfully deleted a student from the student table";
}

// close connection
mysql_close($connection);
?>

PHP Select or Query Record

  • We retrieve all students record from student table, and generate a table list.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select teacher
$sel_query = 'SELECT first_name, last_name FROM student';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>First Name</th><th>Last Name</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';
// close connection
mysql_close($connection);

?>

Display Result

First NameLast Name
JohnyZhar
JacobMilli
IsabellaCatous
MichaelVieva
Emmalee
salinalee
pheankso
lyekwanlee
kilomaotam

PHP Select Multiple Tables

  • Query Multiple Tables
  • We are going to create two more tables, and insert some data into those tables.
  • Table name: subject
  • Insert sample records.
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection)
        or die(mysql_error($connection));

// create subject table
$subject_table = 
   'CREATE TABLE IF NOT EXISTS subject
   (    subject_id INT NOT NULL AUTO_INCREMENT,
        credit_hour INT NOT NULL,
        subject_name VARCHAR(200) NOT NULL,
        PRIMARY KEY(subject_id)
   )ENGINE=InnoDB';

// call this function to create subject table
if (!mysql_query($subject_table, $connection)) {
    echo "Can't create table: " . mysql_error($connection) . "<br/>";
} else {
    echo "You have successfully created subject table <br/>";
}

// insert to the subject table query
$insert_query = '
                    INSERT INTO subject (subject_id, credit_hour, subject_name)
                    VALUES
                    (null,3,"C++"),
                    (null,3,"System Analysis"),
                    (null,2,"Web and HTML"),
                    (null,3,"PHP and Ajax"),
                    (null,2,"Java"),
                    (null,3,"Perl OOP")
                ';
// insert to subject table

if (!mysql_query($insert_query, $connection)) {
    echo "Can't insert subject record : " . mysql_error($connection);
} else {
    echo "You have successfully inserted into subject table  <br/>";
}

// close connection
mysql_close($connection);
?>

Create another table (student_subject table)

  • Table name: student_subject
  • Insert some sample records
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection)
        or die(mysql_error($connection));


// create student subject table
$student_subject_table = 'CREATE TABLE IF NOT EXISTS student_subject
    (   student_subject_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        student_id  INT NOT NULL,
        subject_id  INT NOT NULL
    )ENGINE=InnoDB';

// call this function to create student_subject table
if (!mysql_query($student_subject_table, $connection)) {
    echo "Can't create table: " . mysql_error($connection) . "<br/>";
} else {
    echo "You have successfully created student_subject table <br/>";
}

// insert to the student_subject table query
$insert_query = '
                    INSERT INTO student_subject (student_subject_id, student_id, subject_id)
                    VALUES
                    (null,1,1),
                    (null,1,2),
                    (null,1,4),
                    (null,1,5),

                    (null,2,1),
                    (null,2,2),
                    (null,2,4),
                    (null,2,5),

                    (null,3,1),
                    (null,3,2),
                    (null,3,4),
                    (null,3,5),

                    (null,4,1),
                    (null,4,2),
                    (null,4,3),
                    (null,4,6),


                    (null,5,1),
                    (null,5,2),
                    (null,5,3),
                    (null,5,6),


                    (null,6,1),
                    (null,6,2),
                    (null,6,3),
                    (null,6,6),


                    (null,7,1),
                    (null,7,2),
                    (null,7,3),
                    (null,7,6),


                    (null,8,1),
                    (null,8,4),
                    (null,8,3),
                    (null,8,5),

                    (null,9,1),
                    (null,9,4),
                    (null,9,3),
                    (null,9,5)

                ';
// insert to student_subject table

if (!mysql_query($insert_query, $connection)) {
    echo "Can't insert into student_subject table : " . mysql_error($connection);
} else {
    echo "You have successfully inserted into student_subject table  <br/>";
}

// close connection
mysql_close($connection);
?>

How to query multiple tables

  • Table names: student, subject, student_subject tables.
  • In this example, we query all the students who take C++ class.
  • The C++ class has the ID equal to 1
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select teacher
$sel_query = '
    SELECT stu.student_id, 
           CONCAT(stu.first_name," ",stu.last_name) AS "Full Name",
           sub.subject_name, 
           sub.credit_hour
    FROM 
          student stu, 
          subject sub, 
          student_subject ss
    WHERE 
         stu.student_id = ss.student_id AND
         sub.subject_id = ss.subject_id AND
         sub.subject_id = 1;
    ';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>Full Name</th><th>Subject Name</th><th>Credit Hour</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>'. $row[0] .'</td>';
    echo '<td>'. $row[1] .'</td>';
    echo '<td>'. $row[2] .'</td>';
    echo '<td>'. $row[3] .'</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Multiple Queries

  • PHP Programs generates result for student, subject, student_subject table.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select student table
$sel_query = 'SELECT * FROM student';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<br/>Student Table <br/>';
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>First Name</th><th>Last Name</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';

// select  subject table
$sel_query = 'SELECT subject_id,subject_name,credit_hour FROM subject';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<br/>Student Table <br/>';
echo '<table border="1">';
echo '<tr><th>Subject ID</th><th>Subject Name</th><th>Credit</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';

// select  student_subject table
$sel_query = 'SELECT student_subject_id,subject_id,student_id
        FROM student_subject
        ORDER BY subject_id, student_id';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<br/>student_subject Table <br/>';
echo '<table border="1">';
echo '<tr><th>Student_Subject ID</th><th>subject_id</th><th>student_id</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';

// select students who are taking C++ subject
$sel_query = 'SELECT stu.student_id,
    CONCAT(stu.first_name," ",stu.last_name) AS "Full Name",
    sub.subject_name, sub.credit_hour
    FROM student stu, subject sub, student_subject ss
    WHERE stu.student_id = ss.student_id AND
    sub.subject_id = ss.subject_id AND
    sub.subject_id = 1;
    ';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<br/>Select students who are taking C++ subject <br/>';
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>Full Name</th><th>Subject Name</th><th>Credit Hour</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>'. $row[0] .'</td>';
    echo '<td>'. $row[1] .'</td>';
    echo '<td>'. $row[2] .'</td>';
    echo '<td>'. $row[3] .'</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result


Student Table
Student IDFirst NameLast Name
1JohnyZhar
2JacobMilli
3IsabellaCatous
4MichaelVieva
5Emmalee
6salinalee
7pheankso
8lyekwanlee
9kilomaotam

Subject Table
Subject IDSubject NameCredit
1C++3
2System Analysis3
3Web and HTML2
4PHP and Ajax3
5Java2
6Perl OOP3

student_subject Table
Student_Subject IDsubject_idstudent_id
111
512
913
1314
1715
2116
2517
2918
3319
221
622
1023
1424
1825
2226
2627
1534
1935
2336
2737
3138
3539
341
742
1143
3048
3449
451
852
1253
3258
3659
1664
2065
2466
2867

Select students who are taking C++ subject
Student IDFull NameSubject NameCredit Hour
1Johny ZharC++3
2Jacob MilliC++3
3Isabella CatousC++3
4Michael VievaC++3
5Emma leeC++3
6salina leeC++3
7pheank soC++3
8lyekwan leeC++3
9kiloma otamC++3

Filter return result using WHERE clause

  • Use the WHERE CLAUSE to filter the return data.
  • WHERE CLAUSE can be used in SELECT STATEMENT, UPDATE STATEMENT, and DELETE STATEMENT.

List All Subjects


Subject Table
Subject IDSubject NameCredit
1C++3
2System Analysis3
3Web and HTML2
4PHP and Ajax3
5Java2
6Perl OOP3

Code(subject_table.php)

  • Select only subject has 3 credit hours
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select student who has first name as salina, and last name as lee
$sel_query = 'SELECT * FROM subject WHERE credit_hour=3';

$result = mysql_query($sel_query, $connection) or die(mysql_errno());
echo '<table border="1">';
echo '<tr><th>Subject ID</th><th>Credit Hour</th><th>Subject Name</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';

// close connection
mysql_close($connection);
?>

Display Result

Subject IDCredit HourSubject Name
13C++
23System Analysis
43PHP and Ajax
63Perl OOP

PHP Select Order By

List All Students Without Using Order By Clause

First NameLast Name
JohnyZhar
JacobMilli
IsabellaCatous
MichaelVieva
Emmalee
salinalee
pheankso
lyekwanlee
kilomaotam

Code (student_list.php)

  • Query the student table, and the return record by using ORDER BY last name, and first name.
  • In the last name, the return data start from Catous, lee, Mili, the return data is alphabetical order.
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select student order by first name, and last name
$sel_query = 'SELECT first_name, last_name FROM student ORDER  BY last_name,first_name';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>First Name</th><th>Last Name</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

First NameLast Name
IsabellaCatous
Emmalee
lyekwanlee
salinalee
JacobMilli
kilomaotam
pheankso
MichaelVieva
JohnyZhar

INNER JOIN for joining multiple tables

Join Multiple Tables

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select students who are taking Perl OOP class
$sel_query = '
    SELECT stu.student_id,
           CONCAT(stu.first_name," ",stu.last_name) AS "Full Name",
           sub.subject_name,
           sub.credit_hour
    FROM student stu,
         subject sub,
         student_subject ss
    WHERE
        stu.student_id = ss.student_id AND
        sub.subject_id = ss.subject_id AND
        sub.subject_id = 6;
    ';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>Full Name</th><th>Subject Name</th><th>Credit Hour</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>'. $row[0] .'</td>';
    echo '<td>'. $row[1] .'</td>';
    echo '<td>'. $row[2] .'</td>';
    echo '<td>'. $row[3] .'</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Join multiple table using the INNER JOIN

  • This example is the same as the previous example.
  • In this example uses the INNER JOIN to join three tables together.
  • We get the same result as the previous SELECT STATEMENT.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select students who are taking Perl OOP class (using inner join)
$sel_query = '
        SELECT
            stu.student_id,
            CONCAT(stu.first_name," ", stu.last_name) AS "Full Name",
            sub.subject_name,
            sub.credit_hour
        FROM
            student stu INNER JOIN student_subject ss
                   ON stu.student_id = ss.student_id
                        INNER JOIN subject sub
                   ON ss.subject_id = sub.subject_id
       WHERE sub.subject_id = 6';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>Full Name</th><th>Subject Name</th><th>Credit Hour</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>'. $row[0] .'</td>';
    echo '<td>'. $row[1] .'</td>';
    echo '<td>'. $row[2] .'</td>';
    echo '<td>'. $row[3] .'</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

Student IDFull NameSubject NameCredit Hour
4Michael VievaPerl OOP3
5Emma leePerl OOP3
6salina leePerl OOP3
7pheank soPerl OOP3

Join multiple tables using LEFT JOIN

  • LEFT OUTER JOIN is based on the left table, and it displays null for the right table if the join condition is not matched.
  • Get all students who take PHP and Ajax subject, and as well as students who are not taking any subjects.
  • There are 9 students, and there are 5 out of 9 students who are taking the PHP and Ajax subject.
  • Four other students (Michael Vieva, Emma lee, salina lee, and pheank so) are not taking the PHP and Ajax subject.
<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select students who are taking PHP and AJax subject 
// subject_id=4

$sel_query = '
    SELECT stu.student_id,
           CONCAT(stu.first_name, " ",stu.last_name) AS "full name",
           ss.subject_id
    FROM student stu
        LEFT OUTER JOIN student_subject ss
             ON stu.student_id = ss.student_id
             AND ss.subject_id = 4';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Student ID</th><th>Full Name</th><th>Subject ID</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>' . $row[0] . '</td>';
    echo '<td>' . $row[1] . '</td>';
    echo '<td>' . (empty($row[2]) ? "NULL" : $row[2]) . '</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

Student IDFull NameSubject ID
1Johny Zhar4
2Jacob Milli4
3Isabella Catous4
4Michael VievaNULL
5Emma leeNULL
6salina leeNULL
7pheank soNULL
8lyekwan lee4
9kiloma otam4

Select multiple tables using RIGHT JOIN

  • The RIGHT JOIN to join two tables based on the right table.
  • All records on the right table will display, and records on the left table will display as "NULL" when the condition does not matched.
  • In this program, we try to get information between subject and student relation.
  • Which subject that student_id=4 does not take
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// what subject does a student_id=4 not taking?
$sel_query = '
     SELECT ss.student_subject_id,
            ss.student_id,
            ss.subject_id,
            
            st.subject_name,
            st.credit_hour
        FROM student_subject ss RIGHT OUTER JOIN subject st
            ON ss.subject_id = st.subject_id
            AND ss.student_id=4';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>student subject Id</th><th>student_id</th><th>subject_id</th><th>subject name</th><th>credit hour</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>' . (!empty($row[0]) ? $row[0] : 'NULL') . '</td>';
    echo '<td>' . (!empty($row[1]) ? $row[1] : 'NULL') . '</td>';
    echo '<td>' . (!empty($row[2]) ? $row[2] : 'NULL') . '</td>';
    echo '<td>' . $row[3] . '</td>';
    echo '<td>' . $row[4] . '</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

student subject Idstudent_idsubject_idsubject namecredit hour
1341C++3
1442System Analysis3
1543Web and HTML2
NULLNULLNULLPHP and Ajax3
NULLNULLNULLJava2
1646Perl OOP3

PHP Select Group By

GROUP BY uses to group return data.

Code (groupByExample.php)

  • In this example, we use the group by to group the return data based on the subject id.
<?php

// connect to mysql parameters
$host =     'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$sel_query = 'SELECT subject_id,
    (SELECT su.subject_name FROM subject su WHERE su.subject_id = student_subject.subject_id),
    COUNT(student_id) AS "Total Student"
                FROM student_subject GROUP BY subject_id';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Subject Id</th><th>Subject Name</th><th>Total Student</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>' . $row[0] . '</td>';
    echo '<td>' . $row[1] . '</td>';
    echo '<td>' . $row[2] . '</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

Subject IdSubject NameTotal Student
1C++9
2System Analysis7
3Web and HTML6
4PHP and Ajax5
5Java5
6Perl OOP4

Filter record using HAVING

  • HAVING clause uses to filter the GROUP BY.
  • It returns data when the total student is greater than 5.

Code (GroupBy.php)

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// select students who are taking PHP and AJax subject (subject_id=4)
$sel_query = 'SELECT subject_id,
    (SELECT su.subject_name FROM subject su WHERE su.subject_id = student_subject.subject_id),
    COUNT(student_id) AS "Total Student"
                FROM student_subject GROUP BY subject_id HAVING COUNT(student_id) > 5';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>Subject Id</th><th>Subject Name</th><th>Total Student</th></tr>';
while ($row = mysql_fetch_array($result)) {
    echo '<tr>';
    echo '<td>' . $row[0] . '</td>';
    echo '<td>' . $row[1] . '</td>';
    echo '<td>' . $row[2] . '</td>';
    echo '</tr>';
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Select the largest score

  • Create a new table
  • Table name: score
  • Insert some sample records

Code (insert_score.php)

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

// score table
$create_table = 'CREATE TABLE IF NOT EXISTS score  (
                        score_id INT NOT NULL AUTO_INCREMENT,
                        score DOUBLE NOT NULL,
                        subject varchar(20),
                        PRIMARY KEY(score_id)
                  ) ENGINE=InnoDB';

// call this function to create the score table
if (!mysql_query($create_table, $connection)) {
    echo "Can't create table: " . mysql_error($connection) . "<br/>";
} else {
    echo "You have successfully create score table <br/>";
}

// insert query insert into score table
$insert_query = "
                    INSERT INTO score (score, subject)
                    VALUES
                    (42, 'English'),
                    (53,'MATH'),
                    (32,'PHP'),
                    (78,'MATH'),
                    (80,'JAVA'),
                    (67,'MATH'),
                    (89,'C++'),
                    (56,'MATH'),
                    (63,'PYTH'),
                    (82,'MATH'),
                    (89,'C++'),
                    (89,'JAVA'),
                    (91,'C++'),
                    (79,'C++'),
                    (89,'PHP'),
                    (93,'PHP'),
                    (81,'PERL'),
                    (82,'C++'),
                    (78,'MySQL'),
                    (67,'C++'),
                    (83,'MySQL'),
                    (67,'C++'),
                    (85,'MySQL'),
                    (54,'C++'),
                    (78,'MySQL'),
                    (34,'C++')
                    ";
// insert to score table
if (!mysql_query($insert_query, $connection)) {
    echo "Can't insert score record : " . mysql_error($connection);
} else {
    echo "You have successfully insert into score table";
}
// close connection
mysql_close($connection);
?>

Get the maximum score

  • This program displays the maximum score for each subject.
  • We use the group by "subject" to group the return result according to the subject.
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$query_max = 'SELECT MAX(score), subject FROM score GROUP BY subject';
$result = mysql_query($query_max,$connection) or die(mysql_error());
echo "<table border=\"1\">";
echo "<tr><th>MAX Score</th><th>Subject</th></tr>";
while($row = mysql_fetch_array($result)) {
    echo '<tr><td>'.$row[0]. '</td><td>'. $row[1]. '</td></tr>';
}
echo '</table>';

// close connection
mysql_close($connection);
?>

Display Result

MAX ScoreSubject
91C++
42English
89JAVA
82MATH
85MySQL
81PERL
93PHP
63PYTH

PHP Select MIN

List all the minimum score for each subject. We use the GROUP BY subject to group each select statement.

Code (MixScore.php)

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$query_min = 'SELECT MIN(score), subject FROM score GROUP BY subject';
$result = mysql_query($query_min,$connection) or die(mysql_error());
echo "<table border=\"1\">";
echo "<tr><th>MIN Score</th><th>Subject</th></tr>";
while($row = mysql_fetch_array($result)) {
    echo '<tr><td>'.$row[0]. '</td><td>'. $row[1]. '</td></tr>';
}
echo '</table>';

// close connection
mysql_close($connection);
?>

Display Result

MINScoreSubject
34C++
42English
80JAVA
53MATH
78MySQL
81PERL
32PHP
63PYTH

PHP Select Avg

We want to get average score for each subject, and we use the GROUP BY to group each subject.

Code (avgScore4EachSubject.php)

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$query_avg = 'SELECT AVG(score), subject FROM score GROUP BY subject';
$result = mysql_query($query_avg,$connection) or die(mysql_error());
echo "<table border=\"1\">";
echo "<tr><th>Average Score</th><th>Subject</th></tr>";
while($row = mysql_fetch_array($result)) {
    echo '<tr><td>'. ceil($row[0]). '</td><td>'. $row[1]. '</td></tr>';
}
echo '</table>';

// close connection
mysql_close($connection);
?>

Display Result

Average ScoreSubject
73C++
42English
85JAVA
68MATH
81MySQL
81PERL
72PHP
63PYTH

Sum or total records

  • Total all the score for each subject
  • Use the GROUP BY to group each subject by using SUM keyword to total the score.

Code (TotalScore4EachSubject.php)

<?php
// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$query_a = 'SELECT SUM(score), subject FROM score GROUP BY subject';
$result = mysql_query($query_a,$connection) or die(mysql_error());
echo "<table border=\"1\">";
echo "<tr><th>Total Score</th><th>Subject</th></tr>";
while($row = mysql_fetch_array($result)) {
    echo '<tr><td>'. ceil($row[0]). '</td><td>'. $row[1]. '</td></tr>';
}
echo '</table>';

// close connection
mysql_close($connection);
?>

Display Result

Total ScoreSubject
652C++
42English
169JAVA
336MATH
324MySQL
81PERL
214PHP
63PYTH

PHP Insert Date

  • Create a new table
  • Table name: mycalendar
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection)
        or die(mysql_error($connection));


// create mycalendar table
$mycalendar_table = 'CREATE TABLE IF NOT EXISTS mycalendar
    (   mycalendar_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        wedding_date  DATE DEFAULT 0,
        schedule_date   DATETIME DEFAULT 0,
        access_infor TIMESTAMP DEFAULT 0
    )ENGINE=InnoDB';

// call this function to create mycalendar table
if (!mysql_query($mycalendar_table, $connection)) {
    echo "Can't create table: " . mysql_error($connection) . "<br/>";
} else {
    echo "You have successfully created mycalendar table <br/>";
}

// close connection
mysql_close($connection);
?>

Insert sample records to the mycalendar table

  • Insert record into the mycalendar table.
  • In the insert statement, the $i is from 1 to 5,
  • Insert day: date_add(NOW(),interval $i day)
  • Insert month: date_add(NOW(),interval $i month)
<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");

// select database school
mysql_select_db('school200', $connection)
        or die(mysql_error($connection));

for ($i = 1; $i <= 5; $i++) {
    $sql = "INSERT INTO mycalendar(wedding_date, schedule_date, access_infor)
	VALUES(date_add(NOW(),interval $i day),date_add(NOW(),interval $i month),NOW());";
    if (!mysql_query($sql, $connection)) {
        echo "Error insert into mycalendar " . mysql_error();
    }
    else {
        echo "Insert record into mycalendar <br/>";
    }
}
// close connection
mysql_close($connection);
?>

How to Insert/Update/Add/Delete FROM DATE,DATETIME

// set data with specific date
INSERT INTO mycalendar(mycalendar_id, wedding_date, schedule_date, access_infor)
	VALUES(null,'2001-09-20','2011-04-03 10:30:40','2011-04-03 10:30:40');


// set all data with current date
INSERT INTO mycalendar(mycalendar_id, wedding_date, schedule_date, access_infor)
	VALUES(null,now(),now(),now());

// insert date with curdate() (current date)
INSERT INTO mycalendar(mycalendar_id, wedding_date, schedule_date, access_infor)
	VALUES(null,CURDATE(),now(),now());

// insert date with * delimiter
INSERT INTO mycalendar(mycalendar_id, wedding_date, schedule_date, access_infor)
	VALUES(null,'2010*10*13','2010*10*13 10*10*30','2010*11*22 10*4*20');

// update and add 1 day on the wedding date
UPDATE mycalendar SET wedding_date=DATE_ADD(wedding_date, INTERVAL 1 DAY) WHERE mycalendar_id=1;


// update and substract 5 day from the wedding date
UPDATE mycalendar SET wedding_date=DATE_SUB(wedding_date, INTERVAL 5 DAY) WHERE mycalendar_id=1;


// update and add 30 minutes to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL 30 MINUTE) WHERE mycalendar_id=1;


// update and add 30 minutes and 10 second to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL '30:10' MINUTE_SECOND) WHERE mycalendar_id=1;


// update and substract 30 minutes and 10 second to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_SUB(schedule_date, INTERVAL '30:10' MINUTE_SECOND) WHERE mycalendar_id=1;


// update and add 2 hour and 4 day to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL '4 2' DAY_HOUR) WHERE mycalendar_id=1;


// update and add 3 month to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL 3 MONTH) WHERE mycalendar_id=1;

// update and add 10 seconds to the schedule_date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL 10 SECOND) WHERE mycalendar_id=1;

// update and add hour get from schedule date to the schedule date
UPDATE mycalendar SET schedule_date=DATE_ADD(schedule_date, INTERVAL HOUR(schedule_date) HOUR) WHERE mycalendar_id=2;

PHP Select Date

Code(SelectMyCalendar.php)

<?php

// connect to mysql parameters
$host = 'localhost';
$username = 'root';
$password = 'caojiang';

// connect to mysql server
$connection = mysql_connect($host, $username, $password)
        or die("Unable to connect to the MySQL Server!");
// select database school
mysql_select_db('school200', $connection) or die(mysql_error($connection));

$sel_query = 'SELECT * FROM mycalendar';

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));
echo '<table border="1">';
echo '<tr><th>ID</th><th>Wedding Date</th><th>Schedule Date</th><th>Access Date</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    foreach ($row as $value) {
        echo '<td>' . $value . '</td>';
    }
    echo "</tr>";
}
echo '</table>';
// close connection
mysql_close($connection);
?>

Display Result

IDWedding DateSchedule DateAccess Date
12011-06-212011-07-20 02:30:062011-06-20 02:30:06
22011-06-222011-08-20 02:30:062011-06-20 02:30:06
32011-06-232011-09-20 02:30:062011-06-20 02:30:06
42011-06-242011-10-20 02:30:062011-06-20 02:30:06
52011-06-252011-11-20 02:30:062011-06-20 02:30:06
Navigation
Web
SQL
MISC
References