ganryu

Untitled

Aug 8th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Connect to the database
  5.  *
  6.  * @param string $username
  7.  * @param string $password
  8.  * @param string $dbname
  9.  *
  10.  * @return mysqli the connection to the database
  11.  */
  12. function connect($username, $password, $dbname) {
  13.     $conn = new mysqli("localhost", USERNAME, PASSWORD, DB_NAME);
  14.  
  15.     if ($conn->connect_errno) {
  16.         echo "Failed to connect to MySQL: (" . $conn->connect_errno . ")" . $conn->connect_error;
  17.     }
  18.  
  19.     echo 'Connected succesfully to: ' . $conn->host_info . "\n\n";
  20.  
  21.     return $conn;
  22. }
  23.  
  24. /**
  25.  * Show the columns and rows of a table
  26.  *
  27.  * @param mysqli $conn a connection to the database
  28.  * @param string $tablename
  29.  *
  30.  * @return void // void significa que esta función no retorna nada
  31.  */
  32. function show_table_data($conn, $tablename) {
  33.     $stmt = $conn->prepare("SELECT * FROM " . TABLENAME);
  34.  
  35.     if (!$stmt) {
  36.         echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  37.     }
  38.  
  39.     if (!$stmt->execute()) {
  40.         echo "Execute failed: (" . $stmt->errno . ")" . $stmt->error;
  41.     }
  42.  
  43.     $result = $stmt->get_result();
  44.  
  45.     while ($item = $result->fetch_object()) { // por cada fila de la tabla
  46.         foreach ($item as $key => $attr) { // por cada clave (columna) y atributo (valor) de cada item de la fila
  47.             echo "$key: $attr\n"; // muestro la clave y el atributo
  48.         }
  49.         echo "\n"; //
  50.     }
  51. }
  52.  
  53. const USERNAME = '';
  54. const PASSWORD = '';
  55. const DB_NAME = '';
  56. const TABLENAME = '';
  57.  
  58. $conn = connect(USERNAME, PASSWORD, DB_NAME);
  59. show_table_data($conn, TABLENAME);
Add Comment
Please, Sign In to add comment