App Inventor -  MySQL interface 앱 인벤터 mysql 연결

mysql.php-x.txt mysql.zip

App Inventor - MySQL interface

Probably you want to read this first: What is MySQL and what is a relational database?

You can use this App Inventor example together with a php script on your web server to query your MySQL database on your web server.

Shival Wolf already provided a nice App Inventor Classic - MySQL interface. I now "translated" his example into App Inventor 2 with a few adjustments. Example queries by James.

Setup

  • Put the PHP code on your web server
  • Set the SQLKEY in your app and in the PHP code, they must match for this code to work
  • Setup your database connection information in the php script
  • Try out the code

Special Notes

  • Returns HTTP code 200 for a successful SELECT query
  • Returns HTTP code 201 to return anything that's not a SELECT statement
  • Returns HTTP code 400 for any error with your SQL or setup
  • Make sure to remove any page redirects for mobile devices on your webpage, else the App Inventor app will not be able to access the php script and will get an 404 error: page not found instead.

For questions about App Inventor,
please ask in the App Inventor forum.Thank you.

App Inventor blocks

Please see here for the SQL syntax.

Run Query

Response Received

Display Table

To display the result table, I'm using 2 nested for each loops. In case you are interested in a nicer and more flexible solution, take a look at my dynamic table layout example.

Queries

Further blocks used

Screenshots

PHP Script

I replaced the deprecated original php MySQL API by the php MySQL Improved Extension. However, as the example is designed, this update still will not prevent from SQL Injection attacks, because all queries coming from App Inventor will be executed. You will have to use prepared statements or stored procedures to be on the safe side. See also: SQL Injection Prevention Sheet or do a Google Search do find more about SQL Injections. Also it is recommended to do at least some data validation on the App Inventor side.

New SELECT logic adjusted (result stored in temp. file removed).


Comic provided by xkcd.com. Thank you.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

<?php
/*
 * Written By: ShivalWolf
 * Date: 2011/06/03
 * Contact: Shivalwolf@domwolf.net
 *
 * UPDATE 2011/04/05
 * The code now returns a real error message on a bad query with the mysql error number and its error message
 * checks for magic_quotes being enabled and strips slashes if it is. Its best to disable magic quotes still.
 * Checks to make sure the submitted form is a x-www-form-urlencode just so people dont screw with a browser access or atleast try to
 * Forces the output filename to be JSON to conform with standards
 *
 * UPDATE 2011/06/03
 * Code updated to use the Web Module instead of tinywebdb
 *
 * UPDATE 2013/12/26 and 2014/02/18
 * minor modifications by Taifun, puravidaapps.com
 *
 * UPDATE 2014/07/11
 * mysql API (deprecated) replaced by mysqli by Taifun
 *
 * UPDATE 2015/04/30
 * SELECT logic adjusted (result stored in temp. file removed) by Taifun
 *
 * UPDATE 2016/02/21
 * Bugfix Undefined variable: csv
 */

/************************************CONFIG****************************************/
//DATABSE DETAILS//
$DB_ADDRESS="";
$DB_USER="";
$DB_PASS="";
$DB_NAME="";

//SETTINGS//
//This code is something you set in the APP so random people cant use it.
$SQLKEY="secret";

/************************************CONFIG****************************************/

//these are just in case setting headers forcing it to always expire 
header('Cache-Control: no-cache, must-revalidate');

error_log(print_r($_POST,TRUE));

if( isset($_POST['query']) && isset($_POST['key']) ){                                   //checks if the tag post is there and if its been a proper form post
  //set content type to CSV (to be set here to be able to access this page also with a browser)
  header('Content-type: text/csv');

  if($_POST['key']==$SQLKEY){                                                           //validates the SQL key
    $query=urldecode($_POST['query']);
    if(get_magic_quotes_gpc()){     //check if the worthless pile of crap magic quotes is enabled and if it is, strip the slashes from the query
      $query=stripslashes($query);
    }
    $conn = new mysqli($DB_ADDRESS,$DB_USER,$DB_PASS,$DB_NAME);    //connect

    if($conn->connect_error){                                                           //checks connection
      header("HTTP/1.0 400 Bad Request");
      echo "ERROR Database Connection Failed: " . $conn->connect_error, E_USER_ERROR;   //reports a DB connection failure
    } else {
      $result=$conn->query($query);                                                     //runs the posted query
      if($result === false){
        header("HTTP/1.0 400 Bad Request");                                             //sends back a bad request error
        echo "Wrong SQL: " . $query . " Error: " . $conn->error, E_USER_ERROR;          //errors if the query is bad and spits the error back to the client
      } else {
        if (strlen(stristr($query,"SELECT"))>0) {                                       //tests if it's a SELECT statement
          $csv = '';                                                                    // bug fix Undefined variable: csv
          while ($fieldinfo = $result->fetch_field()) {
            $csv .= $fieldinfo->name.",";
          }
          $csv = rtrim($csv, ",")."\n";
          echo $csv;                                                                    //prints header row
          $csv = '';

          $result->data_seek(0);
          while($row = $result->fetch_assoc()){
            foreach ($row as $key => $value) {
              $csv .= $value.",";
            }
            $csv = rtrim($csv, ",")."\n";
          }
          echo $csv;                                                                    //prints all data rows
        } else {
          header("HTTP/1.0 201 Rows");
          echo "AFFECTED ROWS: " . $conn->affected_rows;       //if the query is anything but a SELECT, it will return the number of affected rows
        }
      }
      $conn->close();                                          //closes the DB
    }
  } else {
     header("HTTP/1.0 400 Bad Request");
     echo "Bad Request";                                       //reports if the secret key was bad
  }
} else {
        header("HTTP/1.0 400 Bad Request");
        echo "Bad Request";
}
?>

 

Test

Tested successfully on HTC Desire running Android 2.2, Samsung Galaxy Tab 10.1N running Android 3.2 and Nexus 5 running Android 4.4.4.
 

Notes

You also might be interested in the video tutorial Connect App Inventor to MySQL Database by Derek Banas.

Questions and Answers

Q1: The instructions say to add the php file to my webserver. Do I just place it in the public directory anywhere?
A: Just put it in a directory which is accessible for everyone.

Q2: Also do I need to enable remote access and add my own domain?
A: See the setup instructions.

Q3: When I insert not latin characters as values to the table I get ???? symbols on my app. My database is UTF 8 General ci. Is there a solution for this?
A: I now tested again and as you can see in the screenshot everything works fine with the default posttext block... I also use UTF-8 in the database settings.

Celog Comunidad provided the following solution:
I use mysqli_set_charset($dbc, "utf8"); and it works fine.

Q4: I installed my mysql server online and when trying your app im getting the following error: Cannot parse text argument to "list from csv table" as a CSV-formatted table. Note: You will not see another error reported for 5 seconds.
A: The list from csv table block is used in the Web1.GotText event. As a test replace the blocks in the then part of the if-then-else statement by
to find out what is going on...

Q5: How can I use INSERT ... FROM SELECT ... statements?
A: See Alex_Mei's solution here. Thank you Alex_Mei.

 

[출처] https://puravidaapps.com/mysql.php

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
101 나인패치(Nine Patch) 이미지란? file 졸리운_곰 2020.10.10 54
100 Python으로 안드로이드 앱 만들기 졸리운_곰 2020.09.30 839
99 [Android] Fragment 를 이용한 탭 만들기 file 졸리운_곰 2020.09.19 52
98 빠르게배우는 안드로이드 Fragment-4(Fragment간 에 데이터전달) file 졸리운_곰 2020.09.19 36
97 빠르게배우는 안드로이드 Fragment-3(Fragment기초 실습) file 졸리운_곰 2020.09.19 58
96 빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경) 졸리운_곰 2020.09.19 38
95 빠르게배우는 안드로이드 Fragment -1 (배경) file 졸리운_곰 2020.09.19 38
94 안드로이드 스튜디오 - 새로 생성한 Activity Class를 쉽게 Manifest에 등록하기. file 졸리운_곰 2020.08.08 52
93 Android Studio Build시 failed linking references 해결방법 file 졸리운_곰 2020.05.05 517
92 [안드로이드 스튜디오] COULD NOT FIND COM.ANDROID.TOOLS.BUILD:GRADLE:3.0.0-BETA6 file 졸리운_곰 2020.05.05 43
91 Android Sync SQLite Database with Server using PHP and MySQL file 졸리운_곰 2019.02.25 7403
90 안드로이드의 MVC, MVP, MVVM 종합 안내서 file 졸리운_곰 2019.01.06 256
89 Getting Started: WebView-based Applications for Web Developers file 졸리운_곰 2018.09.03 264
» App Inventor - MySQL interface 앱 인벤터 mysql 연결 file 졸리운_곰 2018.04.07 2330
87 Connect App Inventor to MySQL Database 앱 인벤터와 mysql 데이터베이스 연결 file 졸리운_곰 2018.04.07 5385
86 Create an API (PHP) 앱 인벤터와 php 통합 file 졸리운_곰 2018.04.07 493
85 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 497
84 Using the WebViewer Control in App Inventor 앱인터에서 웹뷰 컨트롤 사용 file 졸리운_곰 2018.03.24 390
83 WebView Javascript Processor for App Inventor 앱 인벤터 웹뷰 자바스크립트 인터페이스 file 졸리운_곰 2018.03.24 365
82 android webview로 javascript 호출 및 이벤트 받기(연동하기) file 졸리운_곰 2018.03.19 1299
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED