绝想首页

MYSQLI 连接数据库

陈凯qph3nc [沧桑] 2013-04-14 20:41:31 星期日 晴天 查看:399 回复:0 发消息给作者

MYSQLI 连接数据库

$mysqli = new mysqli("localhost", "root", "secret", "test");
if (mysqli_connect_errno(  )) {
   printf("Connect failed: %s ", mysqli_connect_error(  ));
   exit (  );
} else {
   printf("Connect succeeded ");
}
?>

错误检查

1)
    if ($mysqli->query($sql) TRUE) {
         printf("Statement failed %d: (%s) %s " ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
   }
?>
2)
    $mysqli->query($sql) or printf("Statement failed %d: (%s) %s " ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
?>
3)
   $mysqli->query($sql);
   if ($mysqli->errno 0 ) {
           printf("Statement failed %d: (%s) %s " ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
   }
?>

简单无返回查询

$mysqli->query("CREATE TABLE guy_1 (guys_integers INT)");
if ($mysqli->errno 0 ) {
   printf("Statement failed %d: (%s) %s " ,$mysqli->errno,$mysqli->sqlstate,$mysqli->error);
}
?>

返回结果集fetch_object

$sql="SELECT employee_id, surname, salary FROM employees  WHERE salary>95000 AND department_id=1 AND status='G'";
$results=$mysqli->query($sql);
if ($mysqli->errno) { die ($mysqli->errno." ".$mysqli->error); }
while($row=$results->fetch_object(  ))      {
    printf("%d %s %d ",$row->employee_id,$row->surname,$row->salary);
}
?>

使用fetch_row返回结果集 

$sql="SELECT employee_id, surname, salary FROM employees WHERE salary>95000 AND department_id=1 AND status='G'";
$results=$mysqli->query($sql);
if ($mysqli->errno) { die ($mysqli->errno." ".$mysqli->error); }
while($row=$results->fetch_row(  )) {
    printf("%d %s %d ",$row[0],$row[1],$row[2]);
}
?>

事务管理

$mysqli->autocommit(FALSE);
$mysqli->query("UPDATE account_balance SET balance=balance-$tfer_amount  WHERE account_id=$from_account");
if ($mysqli->errno)   {
  printf("transaction aborted: %s ",$mysqli->error);
  $mysqli->rollback(  );
}
else   {
 $mysqli->query("UPDATE account_balance SET balance=balance+$tfer_amount WHERE account_id=$to_account");
 if ($mysqli->errno)  {
     printf("transaction aborted: %s ",$mysqli->error);
     $mysqli->rollback(  );
 }
 else      {
     printf("transaction succeeded ");
     $mysqli->commit(  );
 }
}
?>

prepare语句

$insert_stmt=$mysqli->prepare("INSERT INTO x VALUES(?,?)") or die($mysqli->error);
$insert_stmt->bind_param("is", $my_number,$my_string); #i=integer
for ($my_number = 1; $my_number execute(  ) or die ($insert_stmt->error);
}
$insert_stmt->close(  );
?>

从prepared语句中返回结果集 

$sql="SELECT employee_id,surname,firstname FROM employees WHERE department_id=? AND status=? IMIT 5";
$stmt = $mysqli->prepare($sql);
if ($mysqli->errno0) {die($mysqli->errno.": ".$mysqli->error);}
$stmt->bind_param("is",$input_department_id,$input_status) or die($stmt-error);
$stmt->bind_result( $employee_id,$surname,$firstname)  or die($stmt->error);
$input_department_id=1;
$input_status='G';
$stmt->execute(  );
if ($mysqli->errno0) {die($stmt.errno.": ".$stmt->error) ;}
while ($stmt->fetch(  )) {
   printf("%s %s %s ", $employee_id,$surname,$firstname);
}
?>

获得 Metadata结果集

$metadata = $stmt->result_metadata(  );
$field_cnt = $metadata->field_count;
while ($colinfo = $metadata->fetch_field(  )) {
  printf("Column:   %s ",   $colinfo->name);
  printf("max. Len: %d ",   $colinfo->max_length);
  printf("Type:     %d ", $colinfo->type);
}
?>

调用无结果集的存储过程

$sql = 'call simple_stored_proc(  )';
$mysqli->query($sql);
if ($mysqli->errno) {
   die("Execution failed: ".$mysqli->errno.": ".$mysqli->error);
}
else {
   printf("Stored procedure execution succeeded ");
}
?>

返回单个结果集的存储过程

 

CREATE PROCEDURE department_list( ) READS SQL DATA SELECT department_name,locatio n from departments; 

 

$sql = "call department_list(  )";
$results = $mysqli->query($sql);
if ($mysqli->errno) {
    die("Execution failed: ".$mysqli->errno.": ".$mysqli->error);
}
while ($row = $results->fetch_object(  )) {
    printf("%s %s ", $row->department_name, $row->locatio n);
}
?>

有输入参数和返回结果集的存储过程

 

CREATE PROCEDURE customers_for_rep(in_sales_rep_id INT) READS SQL DATA SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id; 

 

$sql = "CALL customers_for_rep(?)";
$stmt = $mysqli->prepare($sql);
if ($mysqli->errno) {die($mysqli->errno.":: ".$mysqli->error);}
$stmt->bind_param("i", $in_sales_rep_id);
$in_sales_rep_id = 1;
$stmt->execute(  );
if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
$stmt->bind_result($customer_id,$customer_name);
while ($stmt->fetch(  )) {
   printf("%d %s ", $customer_id,$customer_name);
}
?>

输出参数的处理

 

CREATE PROCEDURE sp_rep_customer_count(in_emp_id DECIMAL(8,0), OUT out_cust_count INT) NOT DETERMINISTIC READS SQL DATA BEGIN SELECT count(*) INTO out_cust_count FROM customers WHERE sales_rep_id=in_emp_id; END; 

 

$sql="CALL sp_rep_customer_count(1,@customer_count)";
$stmt = $mysqli->prepare($sql);
if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
$stmt->execute(  );
if ($mysqli->errno) {die($mysqli->errno.": ".$mysqli->error);}
$stmt->close(  );
$results = $mysqli->query("SELECT @customer_count AS customer_count");
$row = $results->fetch_object(  );
printf("Customer count=%d ",$row->customer_count);
?>

多结果集处理

 

CREATE PROCEDURE stored_proc_with_2_results(in_sales_rep_id INT) DETERMINISTIC READS SQL DATA BEGIN SELECT employee_id,surname,firstname FROM employees WHERE employee_id=in_sales_rep_id; SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id; END; 


$query  = "call stored_proc_with_2_results( $employee_id )";
if ($mysqli->multi_query($query)) {
    $result = $mysqli->store_result(  );
    while ($row = $result->fetch_object(  )) {
       printf("%d %s %s ",$row->employee_id,$row->surname,$row->firstname);
    }
    $mysqli->next_result(  );
    $result = $mysqli->store_result(  );
    while ($row = $result->fetch_object(  )) {
        printf("%d %s ",$row->customer_id,$row->customer_name);
     }
}
?>

不确定结果集数的处理

$query  = "call stored_proc_with_2_results( $employee_id )";
if ($mysqli->multi_query($query)) {
   do {
      if ($result = $mysqli->store_result(  )) {
         while ($finfo = $result->fetch_field(  )) {
             printf("%s ", $finfo->name);
         }
         printf(" ");
         while ($row = $result->fetch_row(  )) {
            for ($i=0;$ifield_count;$i++) {
               printf("%s ", $row[$i]);
            }
             printf(" ");
          }
          $result->close(  );
       }
} while ($mysqli->next_result());
}
?>
 

PDO


连接数据库

$dsn = 'mysql:dbname=prod;host=localhost;port=3305';
$user = 'root';
$password = 'secret';
try {
 $dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
 die('Connection failed: '.$e->getMessage(  ));
}
print "Connected ";
?>

简单查询

$sql="CREATE TABLE my_numbers (a_number INT)";
$dbh->exec($sql);
?>

$rows=$dbh->exec("INSERT INTO my_numbers VALUES (1), (2), (3)");
printf("%d rows inserted ",$rows);
?>

错误处理

$sql="CREATE TABLE my_numbers (a_number INT)";
$dbh->exec($sql);
if ($dbh->errorCode(  )'00000') {
 $error_array=$dbh->errorInfo(  );
 printf("SQLSTATE          : %s ",$error_array[0]);
 printf("MySQL error code  : %s ",$error_array[1]);
 printf("Message           : %s ",$error_array[2]);
}
?>

$sql="CREATE TABLE my_numbers (a_number INT)";
$dbh->exec($sql);
if ($dbh->errorCode(  )'00000') {
 die("Error: ".implode(': ',$dbh->errorInfo(  ))." ");
}
?>

事务管理 

$dbh->beginTransaction(  );
$dbh->exec("UPDATE account_balance SET balance=balance-$tfer_amount WHERE account_id=$from_account");
if ($dbh->errorCode(  )'00000') {
   printf("transaction aborted: %s ",implode(': ',$dbh->errorInfo(  )));
   $dbh->rollback(  );
}
else {
   $dbh->exec("UPDATE account_balance SET balance=balance+$tfer_amount WHERE account_id=$to_account");
   if ($dbh->errorCode(  )'00000')   {
       printf("transaction aborted: %s ",implode(': ',$dbh->errorInfo(  )));
       $dbh->rollback(  );
   }
   else  {
      printf("transaction succeeded ");
      $dbh->commit(  );
  }
}
?>

结果集处理

$sql = 'SELECT department_id,department_name FROM departments';
foreach ($dbh->query($sql) as $row) {
 printf("%d %s ",$row['department_id'],$row['department_name']);
}
?>

$sql = 'SELECT department_id,department_name FROM departments';
foreach ($dbh->query($sql) as $row) {
 printf("%d %s ",$row[0],$row[1]);
}
?>

prepare语句

$sql = 'INSERT INTO my_numbers VALUES(1),(2),(3)';
$sth = $dbh->prepare($sql);
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
?>

从prepare语句中返回结果集

$sql='SELECT department_id,department_name FROM departments LIMIT 5';
$sth=$dbh->prepare($sql) or die (implode(':',$sth->errorInfo(  )));
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
while($row=$sth->fetch(  )) {
 printf("%d %s ",$row['department_id'],$row['department_name']);
}
?>

为prepare绑定数据

$sql='SELECT customer_id,customer_name FROM customers  WHERE sales_rep_id=:sales_rep_id  AND contact_surname=:surname';
$sth = $dbh->prepare($sql);
if ($dbh->errorCode(  )'00000') {
   die("Error: ".implode(': ',$dbh->errorInfo(  ))." ");
}
$sth->bindParam(':sales_rep_id', $sales_rep_id, PDO::PARAM_INT);
$sth->bindParam(':surname',      $surname,      PDO::PARAM_STR, 30);
$sales_rep_id=41;
$surname = 'SMITH';
$sth->execute(  );
if ($dbh->errorCode(  )'00000') {
 die("Error: ".implode(': ',$dbh->errorInfo(  ))." ");
}
while($row=$sth->fetch(  )) {
  printf("%d %s ",$row['customer_id'],$row['customer_name']);
}
?>

查询 metadata

$sth = $dbh->prepare("SELECT employee_id,surname,date_of_birth FROM employees where employee_id=1");
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
$cols=$sth->columnCount(  );
for ($i=0; $igetColumnMeta($i);
 printf(" Details for column %d ",$i+1);
 printf("     Name:  %s ",$metadata["name"]);
 printf(" Datatype:  %s ",$metadata["native_type"]);
 printf("   Length:  %d ",$metadata["len"]);
 printf(" Precision: %d ",$metadata["precision"]);
}
?>

执行简单存储过程

$sql='call simple_stored_proc(  )';
$dbh->exec($sql);
if ($dbh->errorCode(  )'00000') {
 die("Error: ".implode(': ',$dbh->errorInfo(  ))." ");
}
?>

单个结果集的存储过程

$sql = 'call stored_proc_with_1_result(  )';
foreach ($dbh->query($sql) as $row) {
 printf("%d %s ",$row[0],$row[1]);
}
?>
 
$sql='call stored_proc_with_1_result(  )';
$sth=$dbh->prepare($sql) or die (implode(':',$sth->errorInfo(  )));
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
while($row=$sth->fetch(  )) {
 printf("%s %s ",$row['department_name'],$row['locatio n']);
}
?>

绑定输入参数

$sql='CALL customers_for_rep(:sales_rep_id,:surname)';
$sth = $dbh->prepare($sql);
if ($dbh->errorCode(  )'00000') {
 die("Error: ".implode(': ',$dbh->errorInfo(  ))." ");
}
$sth->bindParam(':sales_rep_id', $sales_rep_id, PDO::PARAM_INT);
$sth->bindParam(':surname',      $surname,      PDO::PARAM_STR, 30);
$sales_rep_id=41;
$surname = 'SMITH';
$sth->execute(  );
?>

多结果集处理


CREATE PROCEDURE stored_proc_with_2_results(in_sales_rep_id INT) DETERMINISTIC READS SQL DATA BEGIN SELECT employee_id,surname,firstname FROM employees WHERE employee_id=in_sales_rep_id; SELECT customer_id,customer_name FROM customers WHERE sales_rep_id=in_sales_rep_id; END; 


$sth = $dbh->prepare("call stored_proc_with_2_results( $employee_id )");
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
while ($row1=$sth->fetch(  )) {
 printf("%d %s %s ",$row1['employee_id'],$row1['surname'],$row1['firstname']);
}
$sth->nextRowset(  );
while ($row2=$sth->fetch(  )) {
 printf("%d %s ",$row2['customer_id'],$row2['customer_name']);
}
?>

不确定结果集数量的处理 


CREATE PROCEDURE sp_employee_report(in_emp_id decimal(8,0)) READS SQL DATA BEGIN DECLARE customer_count INT; SELECT surname,firstname,date_of_birth FROM employees WHERE employee_id=in_emp_id; SELECT department_id,department_name FROM departments WHERE department_id=(select department_id FROM employees WHERE employee_id=in_emp_id); SELECT count(*) INTO customer_count FROM customers WHERE sales_rep_id=in_emp_id; IF customer_count=0 THEN SELECT 'Employee is not a current sales rep'; ELSE SELECT customer_name,customer_status FROM customers HERE sales_rep_id=in_emp_id; SELECT customer_name,sum(sale_value) FROM sales JOIN customers USING (customer_id) WHERE customers.sales_rep_id=in_emp_id GROUP BY customer_name; END IF; 


   function many_results($dbh, $sql_text) {
      $sth = $dbh->prepare($sql_text);
      $sth->execute() or die(implode(':', $sth->errorInfo(  )));
      do {
          if ($sth->columnCount(  ) > 0) { //是结果集
               //输出字段名
               for ($i = 0; $i < $sth->columnCount(  ); $i ++) {
                   $meta = $sth->getColumnMeta($i);
                   printf("%s ", $meta["name"]);
              }
              printf(" ");
              while ($row = $sth->fetch(  )) {
                   for ($i = 0; $i < $sth->columnCount(  ); $i ++) {
                        printf("%s ", $row[$i]);
                   }
                   printf(" ");
              }
              printf("------------------- ");
          }
      }  while ($sth->nextRowset(  ));
}
?>


输出参数
CREATE PROCEDURE 'sp_rep_customer_count'(in_emp_id DECIMAL(8,0),OUT out_cust_count INT) READS SQL DATA BEGIN SELECT count(*) AS cust_count INTO out_cust_count FROM customers WHERE sales_rep_id=in_emp_id; END ; 

$sql = "call sp_rep_customer_count(?,?)";
$sth = $dbh->prepare($sql)  or die(implode(':', $sth->errorInfo(  )));
$sth->bindParam(1,$sales_rep_id,PDO::PARAM_STR,4000);
$sth->bindParam(2,$customer_count, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute()  or die(implode(':', $sth->errorInfo(  )));
?>

不使用bindParam获得输出参数

$sql="call sp_rep_customer_count(1,@customer_count)";
$sth = $dbh->prepare($sql);
$sth->execute() or die (implode(':',$sth->errorInfo(  )));
$sql="SELECT @customer_count";
foreach ($dbh->query($sql) as $row) {
 printf("Customer count=%d ",$row[0]);
}
?>


顶一下(32 写日记 1248832 239850
分享排行

 

 

留住已经逝去的峥嵘岁月 记住曾经绽现的万种风情 在记忆即将淡漠的时候 来把这些重新回味

Copyright (C) 2008-2014 www.juexiang.com, All Rights Reserved.

京ICP备2023001011号-3   京公网安备11010802011908号

客服QQ 1017160561 违法和不良信息举报电话 13148464312 邮箱 1017160561@qq.com