Lesson 097 php database programming ⑨ - using mysqli extension library (batch execution and transaction control)

Posted by andymelton on Sat, 25 Jan 2020 16:06:31 +0100

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?> 

Own demo:

<?php
    /**
        Exercise: use mysqli of mysqli:multi_query(); query and display at one time ① employee; ② English and Chinese of words table
    */
    //include 'mysqliHelper.php';
    /**
    function __autoload($class_name){
        require_once $class_name.'.php';//This way of automatically loading classes needs to keep the file name and class name consistent for now
    }
    header("content-type:text/html;charset=utf-8");
    //$mysql =  new Mysqlii('localhost','root','tmdqobn','db100') or die (""Wrong.");;

    //$sqls = "select * from employee";
    //$sqls.="select * from words";
    //$res = $mysql->Multi_query($sqls);

    if($mysql->Multi_query($sqls)){
        do{
            if($result==MySQLi->store_result()){
                while($row = $result->fetch_row()){
                foreach ($row as $key=>$value){
                    echo "Key: $key; Value: $value<br />\n";
                }
            }   
            }
        }while($mysql->GetNext_result());
    }

    if($res){
        while($result = $mysql->GetStore_result()){
            while($row = $result->fetch_row()){
                foreach ($row as $key=>$value){
                    echo "Key: $key; Value: $value<br />\n";
                }
            }   
        }
    }
    */

    $mysqli = new MySQLi('localhost','root','tmdqobn','db100') or die ("Database link exception, please try again");;
    $sqls = "select * from employee;";
    $sqls.="select * from words";
    echo "0";
    //If the execution is successful, there is at least one result set
    if($mysqli->multi_query($sqls)){
        echo "1";
        do{
            if($result=$mysqli->store_result()){//Take a result set from mysqli. It must be mysqli result object
                while($row = $result->fetch_row()){
                /// var_dump($row);
                    /**
                    for($i=0;$i<count($row);$i++){
                        echo $row[2]+" .... ";
                    }
                    */
                    foreach ($row as $value){
                        echo "This is the first".$value;
                    }

                    echo "<br/>";

                    // Or write like this

                    foreach ($row as $key=>$val){
                        echo "This is the second".$val;
                    }
                    echo "<br/>";
                }
                if($mysqli->more_results()){//You need to use this to determine whether there are more result sets. If there are no more results that need to be processed in time, a warning will be given.
                    printf("-----------------\n\n\n");
                }else{
                    return;
                }
            }

        }while($mysqli->next_result());
    }
?>

Thing:

The default database engine of mysql is MyISAM, = = transaction and foreign key = = are not supported, and = = InnoDB = = that supports transaction and foreign key can also be used.

InnoDB

mysql> ALTER TABLE account ENGINE=InnoDB;
Query OK, 2 rows affected (0.61 sec)
Records: 2  Duplicates: 0  Warnings: 0

The following has been changed to innodb engine

mysql> show create table account;
+---------+-------------------------------------------------------------------
-----------------------------------------------------------------------+
| Table   | Create Table
                                                                       |
+---------+-------------------------------------------------------------------
-----------------------------------------------------------------------+
| account | CREATE TABLE `account` (
  `id` int(11) NOT NULL,
  `blance` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+---------+-------------------------------------------------------------------
-----------------------------------------------------------------------+
1 row in set (0.00 sec)

Specific control execution code:

<?php
    header("content-type:text/html;charset=utf-8");
    $mysqli = new MySQLi('localhost','root','tmdqobn','db100');
    if($mysqli->connect_error){
        die("Database connection error".$mysqli->connect_error);
    }
    $mysqli->autocommit(0);//First, change the auto commit to false, and then manually execute the commit after the code is written.
    $sql1 = "update account set blance=blance-2 where id=1";
    $sql2 = "update account2 set blance=blance+2 where id=2";
    $b1 = $mysqli->query($sql1) /**or die ($mysqli-error)*/;
    $b2 = $mysqli->query($sql2)  /**or die ($mysqli-error)*/;
    //echo "$b1"."$b1";
    if(!$b1||!$b2){
        echo "Failure rollback";
        $mysqli->rollback();
    }else{
        echo "Success";
        $mysqli->commit();//If successful, call to execute the submission manually
    }

    //Things are often executed for addition, deletion and modification.

    $mysqli->close(); 

    //If the above code is added with $sql2 and the error is written, then $sql1 will be executed successfully and the money will be deducted by 2 yuan, but $sql2 will not be added successfully. This kind of scenario is an error code when it comes to money or points
?>

Database effect:

//No php code executed
mysql> select * from account;
+----+--------+
| id | blance |
+----+--------+
|  1 |    100 |
|  2 |     80 |
+----+--------+
2 rows in set (0.00 sec)

//php executed successfully without error
mysql> select * from account;
+----+--------+
| id | blance |
+----+--------+
|  1 |     98 |
|  2 |     82 |
+----+--------+
2 rows in set (0.00 sec)


//The query effect does not change when php executes any statement in error
mysql> select * from account;
+----+--------+
| id | blance |
+----+--------+
|  1 |     98 |
|  2 |     82 |
+----+--------+
2 rows in set (0.00 sec)
    /**
    In mysql console, you can use things to operate. The specific steps are as follows
    1. Open a thing:
        start transaction
    2. Make a save point
        Savepoint savepoint name
    3. Personal operation
        . . . . . 
    4. If the third step is correct. Then, you can perform commit. If you think there is a problem, roll back the rollback to savepoint name;
    */

//The actual operation code is as follows: rollback code mysql console operation:

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> savepoint a;
Query OK, 0 rows affected (0.05 sec)

mysql> delete from account where id=1;
Query OK, 1 row affected (0.04 sec)

mysql> select * from account;
+----+--------+
| id | blance |
+----+--------+
|  2 |     90 |
|  3 |    400 |
|  4 |    500 |
+----+--------+
3 rows in set (0.00 sec)

mysql> rollback to a;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from account;
+----+--------+
| id | blance |
+----+--------+
|  1 |    100 |
|  2 |     90 |
|  3 |    400 |
|  4 |    500 |
+----+--------+
4 rows in set (0.00 sec)

The characteristics of things acid;

Topics: MySQL PHP Database