Category: mysqli

  • Khóa học miễn phí MySQLi – Using Joins nhận dự án làm có lương

    MySQLi – Using Joins



    In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query.

    You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table.

    You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN.

    Using Joins at the Command Prompt

    Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below −

    Example

    The following examples −

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * FROM tcount_tbl;
    +-----------------+----------------+
    | tutorial_author | tutorial_count |
    +-----------------+----------------+
    |      mahran     |       20       |
    |      mahnaz     |      NULL      |
    |       Jen       |      NULL      |
    |      Gill       |       20       |
    |    John Poul    |        1       |
    |     Sanjay      |        1       |
    +-----------------+----------------+
    6 rows in set (0.01 sec)
    mysql> SELECT * from tutorials_tbl;
    +-------------+----------------+-----------------+-----------------+
    | tutorial_id | tutorial_title | tutorial_author | submission_date |
    +-------------+----------------+-----------------+-----------------+
    |      1      |  Learn PHP     |     John Poul   |    2007-05-24   |
    |      2      |  Learn MySQL   |      Abdul S    |    2007-05-24   |
    |      3      | JAVA Tutorial  |      Sanjay     |    2007-05-06   |
    +-------------+----------------+-----------------+-----------------+
    3 rows in set (0.00 sec)
    mysql>
    

    Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl.

    mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
       → FROM tutorials_tbl a, tcount_tbl b
       → WHERE a.tutorial_author = b.tutorial_author;
    +-------------+-----------------+----------------+
    | tutorial_id | tutorial_author | tutorial_count |
    +-------------+-----------------+----------------+
    |      1      |    John Poul    |        1       |
    |      3      |     Sanjay      |        1       |
    +-------------+-----------------+----------------+
    2 rows in set (0.01 sec)
    mysql>
    

    Using Joins in a PHP Script

    PHP uses mysqli query() or mysql_query() function to get records from a MySQL tables using Joins. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to get records from multiple tables using Join.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    First create a table in MySQL using following script and insert two records.

    create table tcount_tbl(
       tutorial_author VARCHAR(40) NOT NULL,
       tutorial_count int
    );
    insert into tcount_tbl values(''Mahesh'', 3);
    insert into tcount_tbl values(''Suresh'', 1);
    

    Example

    Try the following example to get records from a two tables using Join. −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Using joins on MySQL Tables</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             $sql = ''SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
    				FROM tutorials_tbl a, tcount_tbl b
    				WHERE a.tutorial_author = b.tutorial_author
    
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Author: %s, Count: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_author"],
                      $row["tutorial_count"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output.

    Connected successfully.
    Id: 1, Author: Mahesh, Count: 3
    Id: 2, Author: Mahesh, Count: 3
    Id: 3, Author: Mahesh, Count: 3
    Id: 5, Author: Suresh, Count: 1
    

    MySQL LEFT JOIN

    A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left.

    If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention.

    Example

    Try the following example to understand the LEFT JOIN.

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
       → FROM tutorials_tbl a LEFT JOIN tcount_tbl b
       → ON a.tutorial_author = b.tutorial_author;
    +-------------+-----------------+----------------+
    | tutorial_id | tutorial_author | tutorial_count |
    +-------------+-----------------+----------------+
    |      1      |    John Poul    |       1        |
    |      2      |     Abdul S     |      NULL      |
    |      3      |     Sanjay      |       1        |
    +-------------+-----------------+----------------+
    3 rows in set (0.02 sec)
    

    You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Delete Query nhận dự án làm có lương

    MySQLi – Delete Query



    If you want to delete a record from any MySQL table, then you can use the SQL command DELETE FROM. You can use this command at the mysql> prompt as well as in any script like PHP.

    Syntax

    The following code block has a generic SQL syntax of the DELETE command to delete data from a MySQL table.

    DELETE FROM table_name [WHERE Clause]
    
    • If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table.

    • You can specify any condition using the WHERE clause.

    • You can delete records in a single table at a time.

    The WHERE clause is very useful when you want to delete selected rows in a table.

    Deleting Data from the Command Prompt

    This will use the SQL DELETE command with the WHERE clause to delete selected data into the MySQL table – tutorials_tbl.

    Example

    The following example will delete a record from the tutorial_tbl whose tutorial_id is 3.

    root@host# mysql -u root -p password;
    Enter password:*******
    
    mysql> use TUTORIALS;
    Database changed
    
    mysql> DELETE FROM tutorials_tbl WHERE tutorial_id=3;
    Query OK, 1 row affected (0.23 sec)
    
    mysql>
    

    Deleting Data Using a PHP Script

    PHP uses mysqli query() or mysql_query() function to delete records in a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to delete records in a MySQL table.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to delete a record in a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Deleting MySQL Table record</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             if ($mysqli→query(''DELETE FROM tutorials_tbl where tutorial_id = 4'')) {
                printf("Table tutorials_tbl record deleted successfully.<br />");
             }
             if ($mysqli→errno) {
                printf("Could not delete record from table: %s<br />", $mysqli→error);
             }
    
             $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
    
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output. Here we”ve entered multiple records in the table before running the select script.

    Connected successfully.
    Table tutorials_tbl record deleted successfully.
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Where Clause nhận dự án làm có lương

    MySQLi – WHERE Clause



    We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table.

    Syntax

    The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table −

    SELECT field1, field2,...fieldN table_name1, table_name2...
    [WHERE condition1 [AND [OR]] condition2.....
    
    • You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.

    • You can specify any condition using the WHERE clause.

    • You can specify more than one condition using the AND or the OR operators.

    • A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.

    The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row.

    Here is the list of operators, which can be used with the WHERE clause.

    Assume field A holds 10 and field B holds 20, then −

    Operator Description Example
    = Checks if the values of the two operands are equal or not, if yes, then the condition becomes true. (A = B) is not true.
    != Checks if the values of the two operands are equal or not, if the values are not equal then the condition becomes true. (A != B) is true.
    > Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. (A > B) is not true.
    < Checks if the value of the left operand is less than the value of the right operand, if yes then the condition becomes true. (A < B) is true.
    >= Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. (A >= B) is not true.
    <= Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. (A <= B) is true.

    The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter.

    It is a common practice to search for records using the Primary Key to make the search faster.

    If the given condition does not match any record in the table, then the query would not return any row.

    Fetching Data from the Command Prompt

    This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl.

    Example

    The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay.

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * from tutorials_tbl WHERE tutorial_author = ''Sanjay
    +-------------+----------------+-----------------+-----------------+
    | tutorial_id | tutorial_title | tutorial_author | submission_date |
    +-------------+----------------+-----------------+-----------------+
    |      3      | JAVA Tutorial  |      Sanjay     |    2007-05-21   |
    +-------------+----------------+-----------------+-----------------+
    1 rows in set (0.01 sec)
    
    mysql>
    

    Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * from tutorials_tbl
       WHERE BINARY tutorial_author = ''sanjay
    Empty set (0.02 sec)
    
    mysql>
    

    Fetching Data Using a PHP Script

    PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to select records in a MySQL table using Where Clause.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to select a record using where clause in a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Using Where Clause</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             $sql = ''SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author = "Mahesh"
    
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output. Here we”ve entered multiple records in the table before running the select script.

    Connected successfully.
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Like Clause nhận dự án làm có lương

    MySQLi – Like Clause



    We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records.

    A WHERE clause with the ‘equal to’ sign (=) works fine where we want to do an exact match. Like if “tutorial_author = ”Sanjay””. But there may be a requirement where we want to filter out all the results where tutorial_author name should contain “jay”. This can be handled using SQL LIKE Clause along with the WHERE clause.

    If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause.

    Syntax

    The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table.

    SELECT field1, field2,...fieldN table_name1, table_name2...
    WHERE field1 LIKE condition1 [AND [OR]] filed2 = ''somevalue''
    
    • You can specify any condition using the WHERE clause.

    • You can use the LIKE clause along with the WHERE clause.

    • You can use the LIKE clause in place of the equals to sign.

    • When LIKE is used along with % sign then it will work like a meta character search.

    • You can specify more than one condition using AND or OR operators.

    • A WHERE…LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.

    Using the LIKE clause at the Command Prompt

    This will use the SQL SELECT command with the WHERE…LIKE clause to fetch the selected data from the MySQL table – tutorials_tbl.

    Example

    The following example will return all the records from the tutorials_tbl table for which the author name ends with jay

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * from tutorials_tbl
       → WHERE tutorial_author LIKE ''%jay
    +-------------+----------------+-----------------+-----------------+
    | tutorial_id | tutorial_title | tutorial_author | submission_date |
    +-------------+----------------+-----------------+-----------------+
    |      3      |  JAVA Tutorial |     Sanjay      |    2007-05-21   |
    +-------------+----------------+-----------------+-----------------+
    1 rows in set (0.01 sec)
    
    mysql>
    

    Using LIKE clause inside PHP Script

    PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to select records in a MySQL table using Like Clause.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to select a record using like clause in a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Using Like Clause</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             $sql = ''SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author like "Mah%"
    
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output. Here we”ve entered multiple records in the table before running the select script.

    Connected successfully.
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Select Query nhận dự án làm có lương

    MySQLi – Select Query



    The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP.

    Syntax

    Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −

    SELECT field1, field2,...fieldN
    FROM table_name1, table_name2...
    [WHERE Clause]
    [OFFSET M ][LIMIT N]
    
    • You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.

    • You can fetch one or more fields in a single SELECT command.

    • You can specify star (*) in place of fields. In this case, SELECT will return all the fields.

    • You can specify any condition using the WHERE clause.

    • You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero.

    • You can limit the number of returns using the LIMIT attribute.

    Fetching Data from a Command Prompt

    This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl.

    Example

    The following example will return all the records from the tutorials_tbl table −

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * from tutorials_tbl
    +-------------+----------------+-----------------+-----------------+
    | tutorial_id | tutorial_title | tutorial_author | submission_date |
    +-------------+----------------+-----------------+-----------------+
    |           1 | Learn PHP      | John Poul       | 2007-05-21      |
    |           2 | Learn MySQL    | Abdul S         | 2007-05-21      |
    |           3 | JAVA Tutorial  | Sanjay          | 2007-05-21      |
    +-------------+----------------+-----------------+-----------------+
    3 rows in set (0.01 sec)
    
    mysql>
    

    Fetching Data Using a PHP Script

    PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to select records from a MySQL table.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to select a record from a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Creating MySQL Table</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
    
             $result = $mysqli->query($sql);
    
             if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output. Here we”ve entered multiple records in the table before running the select script.

    Connected successfully.
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    Id: 4, Title: Java Tutorial, Author: Mahesh, Date: 2021
    Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Update Query nhận dự án làm có lương

    MySQLi – Update Query



    There may be a requirement where the existing data in a MySQL table needs to be modified. You can do so by using the SQL UPDATE command. This will modify any field value of any MySQL table.

    Syntax

    The following code block has a generic SQL syntax of the UPDATE command to modify the data in the MySQL table −

    UPDATE table_name SET field1 = new-value1, field2 = new-value2
    [WHERE Clause]
    
    • You can update one or more field altogether.
    • You can specify any condition using the WHERE clause.
    • You can update the values in a single table at a time.

    The WHERE clause is very useful when you want to update the selected rows in a table.

    Updating Data from the Command Prompt

    This will use the SQL UPDATE command with the WHERE clause to update the selected data in the MySQL table tutorials_tbl.

    Example

    The following example will update the tutorial_title field for a record having the tutorial_id as 3.

    root@host# mysql -u root -p password;
    Enter password:*******
    
    mysql> use TUTORIALS;
    Database changed
    
    mysql> UPDATE tutorials_tbl
       → SET tutorial_title = ''Learning JAVA''
       → WHERE tutorial_id = 3;
    Query OK, 1 row affected (0.04 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
    mysql>
    

    Updating Data Using a PHP Script

    PHP uses mysqli query() or mysql_query() function to update records in a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to update records in a MySQL table.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to update a record in a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Updating MySQL Table</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             if ($mysqli→query(''UPDATE tutorials_tbl set tutorial_title = "Learning Java" where tutorial_id = 4'')) {
                printf("Table tutorials_tbl updated successfully.<br />");
             }
             if ($mysqli→errno) {
                printf("Could not update table: %s<br />", $mysqli→error);
             }
             $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
    
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output. Here we”ve entered multiple records in the table before running the select script.

    Connected successfully.
    Table tutorials_tbl updated successfully.
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    Id: 4, Title: Learning Java, Author: Mahesh, Date: 2021
    Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Sorting Results nhận dự án làm có lương

    MySQLi – Sorting Results



    We have seen the SQL SELECT command to fetch data from a MySQL table. When you select rows, the MySQL server is free to return them in any order, unless you instruct it otherwise by saying how to sort the result. But, you sort a result set by adding an ORDER BY clause that names the column or columns which you want to sort.

    Syntax

    The following code block is a generic SQL syntax of the SELECT command along with the ORDER BY clause to sort the data from a MySQL table.

    SELECT field1, field2,...fieldN table_name1, table_name2...
    ORDER BY field1, [field2...] [ASC [DESC]]
    
    • You can sort the returned result on any field, if that field is being listed out.

    • You can sort the result on more than one field.

    • You can use the keyword ASC or DESC to get result in ascending or descending order. By default, it”s the ascending order.

    • You can use the WHERE…LIKE clause in the usual way to put a condition.

    Using ORDER BY clause at the Command Prompt

    This will use the SQL SELECT command with the ORDER BY clause to fetch data from the MySQL table – tutorials_tbl.

    Example

    Try out the following example, which returns the result in an ascending order.

    root@host# mysql -u root -p password;
    Enter password:*******
    mysql> use TUTORIALS;
    Database changed
    mysql> SELECT * from tutorials_tbl ORDER BY tutorial_author ASC
    +-------------+----------------+-----------------+-----------------+
    | tutorial_id | tutorial_title | tutorial_author | submission_date |
    +-------------+----------------+-----------------+-----------------+
    |      2      |  Learn MySQL   |     Abdul S     |    2007-05-24   |
    |      1      |   Learn PHP    |    John Poul    |    2007-05-24   |
    |      3      | JAVA Tutorial  |     Sanjay      |    2007-05-06   |
    +-------------+----------------+-----------------+-----------------+
    3 rows in set (0.42 sec)
    
    mysql>
    

    Verify all the author names that are listed out in the ascending order.

    Using ORDER BY clause inside a PHP Script

    PHP uses mysqli query() or mysql_query() function to get sorted records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

    Syntax

    $mysqli→query($sql,$resultmode)
    

    Sr.No. Parameter & Description
    1

    $sql

    Required – SQL query to get sorted records from a table.

    2

    $resultmode

    Optional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

    Example

    Try the following example to get sorted records from a table −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Sorting MySQL Table records</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl order by tutorial_title asc";
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
                      $row["tutorial_id"],
                      $row["tutorial_title"],
                      $row["tutorial_author"],
                      $row["submission_date"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             mysqli_free_result($result);
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output.

    Connected successfully.
    Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
    Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
    Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
    Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQLi – Handling NULL Values nhận dự án làm có lương

    MySQLi – Handling NULL Values



    We have seen the SQL SELECT command along with the WHERE clause to fetch data from a MySQL table, but when we try to give a condition, which compares the field or the column value to NULL, it does not work properly.

    To handle such a situation, MySQL provides three operators −

    • IS NULL − This operator returns true, if the column value is NULL.

    • IS NOT NULL − This operator returns true, if the column value is not NULL.

    • <=> − This operator compares values, which (unlike the = operator) is true even for two NULL values.

    The conditions involving NULL are special. You cannot use = NULL or != NULL to look for NULL values in columns. Such comparisons always fail because it is impossible to tell whether they are true or not. Sometimes, even NULL = NULL fails.

    To look for columns that are or are not NULL, use IS NULL or IS NOT NULL.

    Using NULL values at the Command Prompt

    Assume that there is a table called tcount_tbl in the TUTORIALS database and it contains two columns namely tutorial_author and tutorial_count, where a NULL tutorial_count indicates that the value is unknown.

    Example

    Try the following examples −

    root@host# mysql -u root -p password;
    Enter password:*******
    
    mysql> use TUTORIALS;
    Database changed
    
    mysql> create table tcount_tbl
       → (
       → tutorial_author varchar(40) NOT NULL,
       → tutorial_count  INT
       → );
    Query OK, 0 rows affected (0.05 sec)
    
    mysql> INSERT INTO tcount_tbl
       → (tutorial_author, tutorial_count) values (''mahran'', 20);
    
    mysql> INSERT INTO tcount_tbl
       → (tutorial_author, tutorial_count) values (''mahnaz'', NULL);
    
    mysql> INSERT INTO tcount_tbl
       → (tutorial_author, tutorial_count) values (''Jen'', NULL);
    
    mysql> INSERT INTO tcount_tbl
       → (tutorial_author, tutorial_count) values (''Gill'', 20);
    
    mysql> SELECT * from tcount_tbl;
    +-----------------+----------------+
    | tutorial_author | tutorial_count |
    +-----------------+----------------+
    |     mahran      |       20       |
    |     mahnaz      |      NULL      |
    |      Jen        |      NULL      |
    |     Gill        |       20       |
    +-----------------+----------------+
    4 rows in set (0.00 sec)
    
    mysql>
    

    You can see that = and != do not work with NULL values as follows −

    mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
    Empty set (0.00 sec)
    
    mysql> SELECT * FROM tcount_tbl WHERE tutorial_count != NULL;
    Empty set (0.01 sec)
    

    To find the records where the tutorial_count column is or is not NULL, the queries should be written as shown in the following program.

    mysql> SELECT * FROM tcount_tbl
       → WHERE tutorial_count IS NULL;
    +-----------------+----------------+
    | tutorial_author | tutorial_count |
    +-----------------+----------------+
    |     mahnaz      |      NULL      |
    |      Jen        |      NULL      |
    +-----------------+----------------+
    2 rows in set (0.00 sec)
    mysql> SELECT * from tcount_tbl
       → WHERE tutorial_count IS NOT NULL;
    +-----------------+----------------+
    | tutorial_author | tutorial_count |
    +-----------------+----------------+
    |     mahran      |       20       |
    |     Gill        |       20       |
    +-----------------+----------------+
    2 rows in set (0.00 sec)
    

    Handling NULL Values in a PHP Script

    You can use the if…else condition to prepare a query based on the NULL value.

    The following example takes the tutorial_count from outside and then compares it with the value available in the table.

    Example

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Handling NULL</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
             $tutorial_count = null;
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             if( isset($tutorial_count )) {
                $sql = ''SELECT tutorial_author, tutorial_count
                   FROM  tcount_tbl
                   WHERE tutorial_count = '' + $tutorial_count;
             } else {
                $sql = ''SELECT tutorial_author, tutorial_count
                   FROM  tcount_tbl
                   WHERE tutorial_count IS NULL
             }
             $result = $mysqli→query($sql);
    
             if ($result→num_rows > 0) {
                while($row = $result→fetch_assoc()) {
                   printf("Author: %s, Count: %d <br />",
                      $row["tutorial_author"],
                      $row["tutorial_count"]);
                }
             } else {
                printf(''No record found.<br />'');
             }
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output.

    Connected successfully.
    No record found.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí Obtaining & Using MySQLi Metadata nhận dự án làm có lương

    MySQLi – Database Info



    Obtaining and Using MySQL Metadata

    There are three types of information, which you would like to have from MySQL.

    • Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement.

    • Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases.

    • Information about the MySQL server − This includes the status of the database server, version number, etc.

    It is very easy to get all this information at the MySQL prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all this information.

    Obtaining the Number of Rows Affected by a Query

    Let is now see how to obtain this information.

    PERL Example

    In DBI scripts, the affected row count is returned by the do( ) or by the execute( ) command, depending on how you execute the query.

    # Method 1
    # execute $query using do( )
    my $count = $dbh→do ($query);
    # report 0 rows if an error occurred
    printf "%d rows were affectedn", (defined ($count) ? $count : 0);
    
    # Method 2
    # execute query using prepare( ) plus execute( )
    my $sth = $dbh→prepare ($query);
    my $count = $sth→execute ( );
    printf "%d rows were affectedn", (defined ($count) ? $count : 0);
    

    PHP Example

    In PHP, invoke the mysql_affected_rows( ) function to find out how many rows a query changed.

    $result_id = mysql_query ($query, $conn_id);
    # report 0 rows if the query failed
    $count = ($result_id ? mysql_affected_rows ($conn_id) : 0);
    print ("$count rows were affectedn");
    

    Listing Tables and Databases

    It is very easy to list down all the databases and the tables available with a database server. Your result may be null if you don”t have the sufficient privileges.

    Apart from the method which is shown in the following code block, you can use SHOW TABLES or SHOW DATABASES queries to get the list of tables or databases either in PHP or in PERL.

    PERL Example

    # Get all the tables available in current database.
    my @tables = $dbh→tables ( );
    
    foreach $table (@tables ){
       print "Table Name $tablen";
    }
    

    PHP Example

    Try the following example to get database info −

    Copy and paste the following example as mysql_example.php −

    <html>
       <head>
          <title>Getting MySQL Database Info</title>
       </head>
       <body>
          <?php
             $dbhost = ''localhost
             $dbuser = ''root
             $dbpass = ''root@123
             $dbname = ''TUTORIALS
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
             $tutorial_count = null;
    
             if($mysqli→connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli→connect_error);
                exit();
             }
             printf(''Connected successfully.<br />'');
    
             if ($result = mysqli_query($mysqli, "SELECT DATABASE()")) {
                $row = mysqli_fetch_row($result);
                printf("Default database is %s<br />", $row[0]);
                mysqli_free_result($result);
             }
             $mysqli→close();
          ?>
       </body>
    </html>
    

    Output

    Access the mysql_example.php deployed on apache web server and verify the output.

    Connected successfully.
    Default database is tutorials
    

    Getting Server Metadata

    There are a few important commands in MySQL which can be executed either at the MySQL prompt or by using any script like PHP to get various important information about the database server.

    Sr.No. Command & Description
    1

    SELECT VERSION( )

    Server version string

    2

    SELECT DATABASE( )

    Current database name (empty if none)

    3

    SELECT USER( )

    Current username

    4

    SHOW STATUS

    Server status indicators

    5

    SHOW VARIABLES

    Server configuration variables


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí MySQL – Installation nhận dự án làm có lương

    MySQLi – Installation



    Downloading MySQL

    The MySQLi extension is designed to work with MySQL version 4.1.13 or newer, So have to download MySQL. All downloads for MySQL are located at . Pick the latest version number for MySQL Community Server you want and, as exactly as possible, the platform you want.

    Installing MySQL on Linux/UNIX

    The recommended way to install MySQL on a Linux system is via RPM. MySQL AB makes the following RPMs available for download on its web site −

    • MySQL − The MySQL database server, which manages databases and tables, controls user access, and processes SQL queries.

    • MySQL-client − MySQL client programs, which make it possible to connect to and interact with the server.

    • MySQL-devel − Libraries and header files that come in handy when compiling other programs that use MySQL.

    • MySQL-shared − Shared libraries for the MySQL client.

    • MySQL-bench − Benchmark and performance testing tools for the MySQL database server.

    The MySQL RPMs listed here are all built on a SuSE Linux system, but they”ll usually work on other Linux variants with no difficulty.

    Now, follow the following steps to proceed for installation −

    • Login to the system using root user.

    • Switch to the directory containing the RPMs −

    • Install the MySQL database server by executing the following command. Remember to replace the filename in italics with the file name of your RPM.

    [root@host]# rpm -i MySQL-5.0.9-0.i386.rpm
    

      Above command takes care of installing MySQL server, creating a user of MySQL, creating necessary configuration and starting MySQL server automatically.

      You can find all the MySQL related binaries in /usr/bin and /usr/sbin. All the tables and databases will be created in /var/lib/mysql directory.

    • This is optional but recommended step to install the remaining RPMs in the same manner −

    [root@host]# rpm -i MySQL-client-5.0.9-0.i386.rpm
    [root@host]# rpm -i MySQL-devel-5.0.9-0.i386.rpm
    [root@host]# rpm -i MySQL-shared-5.0.9-0.i386.rpm
    [root@host]# rpm -i MySQL-bench-5.0.9-0.i386.rpm
    

    Installing MySQL on Windows

    Default installation on any version of Windows is now much easier than it used to be, as MySQL now comes neatly packaged with an installer. Simply download the installer package, unzip it anywhere, and run setup.exe.

    Default installer setup.exe will walk you through the trivial process and by default will install everything under C:mysql.

    Test the server by firing it up from the command prompt the first time. Go to the location of the mysqld server which is probably C:mysqlbin, and type −

    mysqld.exe --console
    

    NOTE − If you are on NT, then you will have to use mysqld-nt.exe instead of mysqld.exe

    If all went well, you will see some messages about startup and InnoDB. If not, you may have a permissions issue. Make sure that the directory that holds your data is accessible to whatever user (probably mysql) the database processes run under.

    MySQL will not add itself to the start menu, and there is no particularly nice GUI way to stop the server either. Therefore, if you tend to start the server by double clicking the mysqld executable, you should remember to halt the process by hand by using mysqladmin, Task List, Task Manager, or other Windows-specific means.

    Verifying MySQL Installation

    After MySQL has been successfully installed, the base tables have been initialized, and the server has been started, you can verify that all is working as it should via some simple tests.

    Use the mysqladmin Utility to Obtain Server Status

    Use mysqladmin binary to check server version. This binary would be available in /usr/bin on linux and in C:mysqlbin on windows.

    [root@host]# mysqladmin --version
    

    It will produce the following result on Linux. It may vary depending on your installation −

    mysqladmin  Ver 8.23 Distrib 5.0.9-0, for redhat-linux-gnu on i386
    

    If you do not get such message, then there may be some problem in your installation and you would need some help to fix it.

    Execute simple SQL commands using MySQL Client

    You can connect to your MySQL server by using MySQL client using mysql command. At this moment, you do not need to give any password as by default it will be set to blank.

    So just use following command

    [root@host]# mysql
    

    It should be rewarded with a mysql> prompt. Now, you are connected to the MySQL server and you can execute all the SQL command at mysql> prompt as follows −

    mysql> SHOW DATABASES;
    +----------+
    | Database |
    +----------+
    | mysql    |
    | test     |
    +----------+
    2 rows in set (0.13 sec)
    

    Post-installation Steps

    MySQL ships with a blank password for the root MySQL user. As soon as you have successfully installed the database and client, you need to set a root password as follows −

    [root@host]# mysqladmin -u root password "new_password";
    

    Now to make a connection to your MySQL server, you would have to use the following command −

    [root@host]# mysql -u root -p
    Enter password:*******
    

    UNIX users will also want to put your MySQL directory in your PATH, so you won”t have to keep typing out the full path every time you want to use the command-line client. For bash, it would be something like −

    export PATH = $PATH:/usr/bin:/usr/sbin
    

    Running MySQL at boot time

    If you want to run MySQL server at boot time, then make sure you have following entry in /etc/rc.local file.

    /etc/init.d/mysqld start
    

    Also,you should have mysqld binary in /etc/init.d/ directory.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc