Apache php mysql android

Apache php mysql android

Доброго времени суток, сегодня я вам расскажу как запустить Apache, PHP 7 и Mysql у себя на телефоне.

Что нам понадобится?
Ровные руки, телефон на базе Андроид, желательно не ниже четверки и интернет(для скачивания приложений, дальше не нужно).

Нам надо скачать:
HTTP Server, PHP Server и MariaDB Server.

Дальше скачиваем уже в самих приложениях загрузочные файлы, версию Apache, PHP и Mysql сами выбирайте, можно просто самые новые версии качать.

Теперь мы все скачали, что же дальше?

Дальше нам надо зайти в настройки HTTP Server и найти там пункт CGI.

Если не нашли, то я хз чо тут делать, очки купите :/

Теперь смело запускаем HTTP и MariaDB Server.

По стандарту приложение запускает по этому адресу: 0.0.0.0:8000

Но можете выбрать другой, так же и с Mysql, только у Mysql порт: 3306
Т.е подключение надо делать на: 0.0.0.0:3306

Если апач и бд запустилось, то надо бы это поверить.

Это значит, что апач работает.

Давайте проверим теперь, работает ли наша база данных.

Создаем файл index.php в /htdocs — этот путь будет указан в приложении Апача, там найдете.

Там же создадим .htacces с кодом:
DirectoryIndex index.php
Тем самым мы указываем индексный файл.

Вы там увидели include какого-то Base.php — это мини-библиотека(обертка) моего друга для работы с PDO.
Скачать по ссылке(ZIP):
https://github.com/PandCar/Base/archive/master.zip

Это значит, что все работает :3

На этом все, удачи вам в освоении программирования)

И че? вот нахрена тебе апач в телефоне? вот мне например без многооконности даже печатать что то в лом тупо копирую элементы кода из одного файла в другой да и базу опять же видишь в анроиде даже тестить что то маразм
________
посл. ред. 10.06.2019 в 18:36; всего 1 раз(а); by skitalec

skitalec, Не у каждрого есть пк или ноут.

Да и некоторым просто интересно потестить разные скрипты на телефоне.

Короче, разные ситуации бывают и вопрос этот для меня был востребован, меня прост задолбали спрашивать про php на андроиде.

skitalec (10.06.2019 в 18:35)
И че? вот нахрена тебе апач в телефоне? вот мне например без многооконности даже печатать что то в лом тупо копирую элементы кода из одного файла в другой да и базу опять же видишь в анроиде даже тестить что то маразм

Изображение

——
65071_Screenshot_20190610213202747_ru.kslabs.ksweb.png (133.3 Kb)
Скачиваний: 51

Источник

Running amp apache mysql php on android

WAMP is acronym for Windows, Apache, MySQL and PHP, Perl, Python. WAMP software is one click installer which creates an environment for developing PHP, MySQL web application. d and name Here the Scenario is to insert ID and NAME of employee from the EDITTEXT to MYSQL server database The Global Variables are For Activity Code Method of inserting data here is insert2.php file Second Edit:- For reading data i have done asyntask Here the data is displayed in a listview.

Running AMP (apache mysql php) on Android

Finally — someone has released the full package!

Bit Web Server (AMP; also see their homepage) stack running on Android. No hacking required. $2 to pay though!

If you are looking for a stack for iOS then the cydia-ios-lighttpd-php-mysql-web-stack does the trick: Should run lighttpd + php 5.4 + mysql — unfortunately only on jailbroken devices.

Edit: In case anyone is interested I have switched to Windows 8 tablet which happily runs all of the opensource AMP stacks. Runs very nicely and with a bit of Bootstrap styling I have a full feature sales order «app» for nothing. Little bit of code to sync back to the online version — no need to spend $50 per month per user on HandShake or similar.

If you’re not stuck with PHP and MySql, then another option would be to use Html 5.

Then your site can run in the browser on iOS and (most) versions of android. By using offline cache and a local database, you could avoid using PhoneGap, etc. You could also use jQuery if you like.

You would, however, have to use javascript to access the local database instead of php. Also — since the sqlite support is being dropped in Html 5, you would have to use local storage or indexed db. I find the former much simpler and fine for my purpose.

BTW — for developing, Google Chrome has nice tools for debugging javascript.

I’m looking for the same thing, but all I found was PAW Server.

I haven’t tried it but I was told it should work just like a standard AMP install but without the mySQL.

The database is what I’m finding to be a pain. I might just have to use a remote DB and local web server to feed from that, but that will mean I’ll need to have it always online.

How to make «portable» web app with Apache, Php, and, The web app is placed in a folder and inside of it, there are Apache, PHP, the database like MySQL or PostgreSQL, and the web source. If we want to access it, there is just a shortcut in the Desktop, and when we click that, the browser is opened and point to an URL with a particular port like localhost:8888. …

Running AMP (apache mysql php) on Android

Running AMP (apache mysql php) on AndroidMySQL [ Ext for Developers : https://www.hows.tech/p/recommended.html ] Running AMP ( apache mysql

Running AMP (apache mysql php) on Android

Running AMP (apache mysql php) on Android — PHP [ Ext for Developers : https://www.hows.tech/p/recommended.html ] Running AMP (apache mysql …

MySQL : Running AMP (apache mysql php) on Android

MySQL : Running AMP (apache mysql php) on Android [ Beautify Your Computer : https://www.hows.tech/p/recommended.html ] MySQL : Running …

Connect mySQL with Android

EDIT: First Create A database Name suppose dbname in MySql in wamp or in your server and create a table named emp_info in which two fields are added id and name

Here the Scenario is to insert ID and NAME of employee from the EDITTEXT to MYSQL server database

 String name; String id; InputStream is=null; String result=null; String line=null; int code; 
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class add extends Activity < String name; String id; InputStream is=null; String result=null; String line=null; int code; String tobed = null; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.add); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); final EditText e_id=(EditText) findViewById(R.id.editText1); final EditText e_name=(EditText) findViewById(R.id.editText2); Button insert=(Button) findViewById(R.id.button1); insert.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < // TODO Auto-generated method stub name = e_name.getText().toString(); insert(); >>); > > 
public void insert() < ArrayListnameValuePairs = new ArrayList(); // put the values of id and name in that variable nameValuePairs.add(new BasicNameValuePair("id",id)); nameValuePairs.add(new BasicNameValuePair("name",name)); try < HttpClient httpclient = new DefaultHttpClient(); // here is the php file // for local use for example if you are using wamp just put the file in www/project folder HttpPost httppost = new HttpPost("http://10.0.2.2/project/insert2.php"); // if the file is on server HttpPost httppost = new HttpPost("http://example.com/insert2.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.e("pass 1", "connection success "); >catch(Exception e) < Log.e("Fail 1", e.toString()); Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show(); >try < BufferedReader reader = new BufferedReader (new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) < sb.append(line + "\n"); >is.close(); result = sb.toString(); Log.e("pass 2", "connection success "); > catch(Exception e) < Log.e("Fail 2", e.toString()); >try < // get the result from php file JSONObject json_data = new JSONObject(result); code=(json_data.getInt("code")); if(code==1) < Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show(); >else < Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show(); >> catch(Exception e) < Log.e("Fail 3", e.toString()); Log.i("tagconvertstr", "["+result+"]"); >> 
 $flag['code']=0; // query for insertion // table name emp_info and its fields are id and name if($r=mysql_query("insert into emp_info values('$name','$id') ",$con)) < // if query runs succesfully then set the flag to 1 that will be send to client app $flag['code']=1; echo"hi"; >// send result to client that will be 1 or 0 print(json_encode($flag)); //close mysql_close($con); ?> 

Second Edit:-

For reading data i have done asyntask

Here the data is displayed in a listview.

public class read extends Activity < private String jsonResult;// // use this if your file is on server private String url = "http://exmaple.com/read.php"; // use this if you are locally using // private String url = "http://10.0.2.2/project/read.php"; private ListView listView; Context context; String name; String id; InputStream is=null; String result=null; String line=null; int code; @Override protected void onCreate(Bundle savedInstanceState)

accessWebService method

 public void accessWebService() < JsonReadTask task = new JsonReadTask(); task.execute(new String[] < url >); > 

for JsonReadTask class

private class JsonReadTask extends AsyncTask  < // doInBackground Method will not interact with UI @Override protected String doInBackground(String. params) < // the below code will be done in background HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); try < HttpResponse response = httpclient.execute(httppost); jsonResult = inputStreamToString( response.getEntity().getContent()).toString(); >catch (ClientProtocolException e) < e.printStackTrace(); Log.e("Fail 12", e.toString()); >catch (IOException e) < Log.e("Fail 22", e.toString()); e.printStackTrace(); >return null; > private StringBuilder inputStreamToString(InputStream is) < String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try < while ((rLine = rd.readLine()) != null) < answer.append(rLine); >> catch (IOException e) < // e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error. " + e.toString(), Toast.LENGTH_LONG).show(); >return answer; > // after the doInBackground Method is done the onPostExecute method will be called @Override protected void onPostExecute(String result) < // here you can interact with UI ListDrwaer(); >>// end async task 

ListDrawaer Method

 // build hash set for list view public void ListDrwaer() < List> employeeList = new ArrayList>(); try < // getting data from server JSONObject jsonResponse = new JSONObject(jsonResult); if(jsonResponse != null) < JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info"); // get total number of data in table for (int i = 0; i < jsonMainNode.length(); i++) < JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); String name = jsonChildNode.optString("name"); // here name is the table field String number = jsonChildNode.optString("id"); // here id is the table field String outPut = name + number ; // add two string to show in listview employeeList.add(createEmployee("employees", outPut)); >> > catch (JSONException e) < Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show(); >SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] < "employees" >, new int[] < android.R.id.text1 >); listView.setAdapter(simpleAdapter); > private HashMap createEmployee(String name, String number) < HashMapemployeeNameNo = new HashMap(); employeeNameNo.put(name, number); return employeeNameNo; > > 

and your read.php file code

 > mysql_close($con); echo json_encode($json); ?> 

and if you want to check you internet connection before using this insertion and reading use this method .. i.e put this method in if else statement

 public boolean isOnline() < ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) < return true; >return false; > 

For Updation and deletion use the insert method to pass the values to the server and just change the query of insert2.php to update ones like this

if($r=mysql_query("UPDATE emp_info SET employee_name = '$name' WHERE employee_name = '$id'",$con))
if($r=mysql_query("DELETE FROM emp_info WHERE employee_name = '$name'",$con))

Also when you have learn this, the next task you should learn threading and Asyntask to make it more improved as working on main thread is not good in android. just put this insert method in Asyntask as i have mentioned in Reading method so that UI dont get disturbed and the internet thing is done in background.

for new version of php add this line after

error_reporting(E_ALL ^ E_DEPRECATED); 

Connecting to MySQL database using PHP for Android, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

How to use php mysql with Android for post and get data?

There is no direct connection between Android and MySql & PHP.
In your screen shot you see phpMyAdmin this is just a UI for MySQL database (there are more).
To achieve your goal you need a server, for example wamp which contains Apache, MySql & PHP.
With PHP and MySql you need to create a web services.
After you create these services you can write an Android application that call these services.

You need to write a webservice which will get the data from your mysql database and send it to your android app.

First of all you need a server (Ex: Wamp). WAMP is acronym for Windows, Apache, MySQL and PHP, Perl, Python. WAMP software is one click installer which creates an environment for developing PHP, MySQL web application. By installing this software you will be installing Apache, MySQL and PHP

Second Write a php script on your server which can retrieve the required data from the MySQL database. Encode the retrieved data inside a JSON object and send it back to your app.

This tutorial excellently illustrates what you are looking for. Hope it helps. URL: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

To connect to the MySQL database you need to have something like a connector.php and it would be good to use a class for writing, reading, updating and deleting the data. Then call to JSON.

JSONObject json = jsonParser.makeHttpRequest(url_create_entry, "POST", params);

Php - Connect mySQL with Android, Here is the example. EDIT: First Create A database Name suppose dbname in MySql in wamp or in your server and create a table named emp_info in which two fields are added id and name Here the Scenario is to insert ID and NAME of employee from the EDITTEXT to MYSQL server database. The Global …

Источник

Читайте также:  Document name src javascript
Оцените статью