Advertisement
Guest User

Untitled

a guest
Jul 11th, 2016
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. ## php set mysql demo
  2.  
  3. * process-oriented model
  4.  
  5. ```php
  6. $host = 'localhost';
  7. $user = 'root';
  8. $pass = '';
  9. $data_base = 'test';
  10.  
  11. mysql_connect($host, $user, $pass);
  12. mysql_select_db($data_base);
  13.  
  14. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  15. $data = array(
  16. 'status' => 100,
  17. 'desc' => 'wrong method'
  18. );
  19. echo json_encode($data);
  20. exit();
  21. }
  22. if (!array_key_exists('action', $_POST)) {
  23. $data = array(
  24. 'status' => 100,
  25. 'desc' => 'none action'
  26. );
  27. echo json_encode($data);
  28. exit();
  29. }
  30. foreach ($_POST as $key => $value) {
  31. $$key = $value;
  32. }
  33. switch ($action) {
  34. case 'hecheng':
  35. mysql_query("INSERT INTO `testtable`
  36. (
  37. `create_time`,
  38. `owner_id`,
  39. ) VALUES (
  40. NOW(),
  41. $owner_id
  42. )");
  43. $insert_id = mysql_insert_id();
  44. $data = array(
  45. 'status'=>200,
  46. 'desc'=>'success',
  47. 'data'=> array(
  48. 'id'=>$insert_id
  49. )
  50. );
  51. echo json_encode($data);
  52. break;
  53. }
  54. ```
  55.  
  56. * object-oriented model
  57.  
  58. ```php
  59. $host = 'localhost';
  60. $user = 'root';
  61. $pass = '';
  62. $data_base = 'test';
  63.  
  64. $mysqli = new mysqli($host, $user, $pass, $data_base);
  65. if (mysqli_connect_errno()) {
  66. printf("Connect failed: %s\n", mysqli_connect_error());
  67. exit();
  68. }
  69.  
  70. // insert
  71. $stmt = $mysqli->prepare(
  72. "
  73. INSERT INTO `testtable`
  74. (
  75. `create_time`,
  76. `owner_id`,
  77. `nickname`
  78. )
  79. VALUES
  80. (
  81. NOW(),
  82. ?,
  83. ?
  84. )
  85. ");
  86. $stmt->bind_param('sssii', intval($owner_id), $nickname);
  87. $stmt->execute();
  88. $meta = $stmt->result_metadata();
  89. $insert_id = 'wrong';
  90. if (!$meta) {
  91. $insert_id = $stmt->insert_id;
  92. }
  93. $data = array(
  94. 'status'=>200,
  95. 'desc'=>'success',
  96. 'data'=> array(
  97. 'id'=>$insert_id
  98. )
  99. );
  100. echo json_encode($data);
  101. $stmt->close();
  102.  
  103. // query
  104.  
  105. if ($stmt = $mysqli->prepare("SELECT * FROM `testtable` WHERE id=$id")) {
  106. $stmt->execute();
  107.  
  108. $meta = $stmt->result_metadata();
  109. while ($field = $meta->fetch_field())
  110. {
  111. $params[] = &$row[$field->name];
  112. }
  113.  
  114. call_user_func_array(array($stmt, 'bind_result'), $params);
  115.  
  116. while ($stmt->fetch()) {
  117. foreach($row as $key => $val)
  118. {
  119. $c[$key] = $val;
  120. }
  121. $result[] = $c;
  122. }
  123. //print_r($result);
  124. $stmt->close();
  125. }
  126.  
  127. echo json_encode($result);
  128. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement