PHP MYSQL database operation (10.11 Day 19)

A, connecting and disconnecting the database

  1, using the mysqli extension (recommended), only for mysql database

    Object-oriented approach

Copy the code
      the mysqli new new CON = $ (IP, User, password); 
      IF ($ con-> connect_error) { 
        the dir (. "connection failed" $ con-> connect_error); 
      } the else { 

        echo "connection successful"; 
      } 
      $ con-> cloase ();
Copy the code

    Direct method (process-oriented)

Copy the code
      $con = mysqli_connect(ip,user,password);
      if($con){
        echo mysqli_connect_error();
      } else {
        echo "连接成功";
      }
      mysqli_close($con)
Copy the code

   2, using mysql extension (PHP <= 5.0), starting in 2012 is not recommended 

   3, the use of PDO (php data objects) technology (preventing sql injection) object-oriented manner (recommended), 12 kinds can be applied to the database

Copy the code
      try{
        $con = new PDO("mysql:host=ip;",user,passwod);
        echo "连接成功";
      }
      catch(PDOException $error){
        echo $error->getMessage();
      }
      $con = null;
Copy the code

Second, the implementation of sql statement

Copy the code
  SQL = $ "cteate db_name Database"; 
  $ Result = "the mysqli_query (CON $, $ SQL)"; 
  IF () { 
    echo "success"; 
  } the else { 
    echo mysqli_error ($ CON); // print error 
  }
Copy the code

   mysqli_close ($ con) // close the database

   Record mysqli_num_rows ($ result) // number of queries

   mysqli_field_count ($ result) // queries column

   mysql_fetch_all ($ result) // query all data

   mysqli_fetch_assoc ($ result) // a result of the execution into an array, the associated array

  Print all arrays

   while ($rows = mysqli_fetch_assoc($result)) {
      print_r($row);
   }

Guess you like

Origin www.cnblogs.com/liujizhou/p/11706591.html