我在mysql服务器上有个问题,我有一个android应用程序,它向服务器发送这些数据:语音、评论、标题、微调器和其他,我用代码发送语音,用asynchttpclient库发送其他文本数据。当我收到一个用户的所有数据时,我希望所有的数据都保存在一行
id title description category voice status
1 hi hi 1 upload/voice.mp3 1
但当用户将此数据发送到php文件时,sql会生成如下两行:
id title description category voice status
1 hi hi 1 upload/ 1
和
id title description category voice status
2 hi hi 1 upload/voice.mp3 1
我有什么问题?这是我的php代码:
<?php
send();
function connectToDatabase() {
$connection=mysqli_connect("***", "***", "***", "***");
if (mysqli_connect_errno()) {
echo "Error is" . mysqli_connect_error();
}
mysqli_set_charset($connection,"utf8");
return $connection;
}
function send() {
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
}
$connection = connectToDatabase();
$Username = $_REQUEST['Username'];
$Title = $_REQUEST['Title'];
$Desc = $_REQUEST['Desc'];
$City = $_REQUEST['City'];
$Cate = $_REQUEST['Cate'];
$file_path=$file_path;
$Timee = date("Y/m/d G:i");
$result = mysqli_query($connection,"insert into banners
(Username,Title,Descript,City,Cate,Date,voice,Status)
values
('$Username','$Title','$Desc','$City','$Cate','$Timee','$file_path','1')"
);
if($result!=""){
print "ok";
}else {
print "no";
}
}
return;
?>
以及我在android中的“向服务器发送数据”活动:
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class New_Banners extends AppCompatActivity {
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
// Development by SmartMob (Manager : Mohammad Mokhles)
EditText new_banners_title, new_banners_desc;
Spinner new_banners_city, new_banners_cate;
Button StartButton, StopButton;
String[] cates = {"لوازم الکترونیکی => موبایل", "لوازم الکترونیکی => تبلت", "لوازم الکترونیکی => لپ تاپ", "املاک => خرید و فروش", "املاک => رهن و اجازه", "کاریابی => بازاریاب", "کاریابی => مهندس", "کاریابی => پزشک"};
String[] cates_code = {"1,1", "1,2", "1,3", "2,1", "2,2", "3,1", "3,2", "3,3"};
String patch = "";
String city = "";
String cate = "";
Snackbar snackbar;
MediaRecorder audiocapture;
MaterialDialog wait;
FloatingActionButton btn_send, btn_send_ch;
MediaRecorder recorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_banners);
ini();
ArrayAdapter<String> adapter_city = new ArrayAdapter<String>(getApplicationContext(), R.layout.row_spinner_two, citys);
new_banners_city.setAdapter(adapter_city);
new_banners_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
city = citys_code[position];
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
city = citys_code[0];
}
});
ArrayAdapter<String> adapter_cate = new ArrayAdapter<String>(getApplicationContext(), R.layout.row_spinner_two, cates);
new_banners_cate.setAdapter(adapter_cate);
new_banners_cate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cate = cates_code[position];
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
cate = cates_code[0];
}
});
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
tempFilename = System.currentTimeMillis()+".mp3";
recorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+tempFilename);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
StopButton.setVisibility(View.GONE);
((Button) findViewById(R.id.StartButton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
recorder.prepare();
recorder.start();
StartButton.setVisibility(View.GONE);
StopButton.setVisibility(View.VISIBLE);
Snackbar snackbar = Snackbar
.make(new_banners_title, " " +
"D:", Snackbar.LENGTH_LONG);
snackbar.show();
} catch (Exception e) {
}
}
});
((Button) findViewById(R.id.StopButton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
recorder.stop();
StopButton.setVisibility(View.GONE);
Snackbar snackbar = Snackbar
.make(new_banners_title, " " +
"عه:))", Snackbar.LENGTH_LONG);
snackbar.show();
} catch (Exception e) {
}
}
});
btn_send.setVisibility(View.GONE);
btn_send_ch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(New_Banners.this, webview.class);
startActivity(intent);
btn_send.setVisibility(View.VISIBLE);
btn_send_ch.setVisibility(View.GONE);
}
});
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (new_banners_title.getText().toString().equals("") || new_banners_title.length() < 10) {
Snackbar snackbar = Snackbar
.make(new_banners_title, " " +
"10 و", Snackbar.LENGTH_LONG);
snackbar.show();
} else if (new_banners_desc.getText().toString().equals("") || new_banners_desc.length() < 30) {
Snackbar snackbar = Snackbar
.make(new_banners_title, " " +
" حداقل D:", Snackbar.LENGTH_LONG);
snackbar.show();
} else {
wait.show();
send(new_banners_title.getText().toString(), new_banners_desc.getText().toString(), city, cate);
}
}
});
}
private void send(String Title, String Desc, String City, String Cate) {
AsyncHttpPost post = new AsyncHttpPost(
"http://myserver.zili.ir/new_banners.php"
);
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("Username", MainActivity.sp.getString("Username", null));
body.addStringPart("Title", Title);
body.addStringPart("Desc", Desc);
body.addStringPart("City", City);
body.addStringPart("Cate", Cate);
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
@Override
public void onCompleted(final Exception e, AsyncHttpResponse source, String result) {
if (e != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
wait.dismiss();
Toast.makeText(New_Banners.this, "خطا در برقراری اتصال با سرور !", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
}
if (result.equals("ok")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
wait.dismiss();
// Toast.makeText(New_Banners.this, "tnx", Toast.LENGTH_LONG).show();
finish();
}
});
} else if (result.equals("no")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
wait.dismiss();
Toast.makeText(New_Banners.this, "خطا در ثبت آگهی", Toast.LENGTH_LONG).show();
}
});
} else if (result.equals("error")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
wait.dismiss();
Toast.makeText(New_Banners.this, "خطا در ثبت !", Toast.LENGTH_LONG).show();
}
});
}
}
});
dialog.show();
new Thread(new Runnable() {
@Override
public void run() {
uploadFile(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+tempFilename) ;
}
}).start();
}
String TAG = "tag";
String tempFilename = "";
public int uploadFile(final String selectedFilePath) {
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length - 1];
if (!selectedFile.isFile()) {
dialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(New_Banners.this, "file notfound", Toast.LENGTH_SHORT).show();
//tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL("http://myserver.zili.ir/new_banners.php");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable, maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0) {
//write the bytes read from inputstream
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(New_Banners.this, "file uplaod successful", Toast.LENGTH_SHORT).show();
// tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(New_Banners.this, "File Not Found", Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(New_Banners.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(New_Banners.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
private void ini() {
wait = new MaterialDialog.Builder(New_Banners.this)
.content("لطفا صبر کنید ...")
.progress(true, 0)
.cancelable(false)
.build();
btn_send = (FloatingActionButton) findViewById(R.id.btn_send);
new_banners_title = (EditText) findViewById(R.id.new_banners_title);
new_banners_desc = (EditText) findViewById(R.id.new_banners_desc);
StartButton = (Button) findViewById(R.id.StartButton);
StopButton = (Button) findViewById(R.id.StopButton);
new_banners_city = (Spinner) findViewById(R.id.new_banners_city);
new_banners_cate = (Spinner) findViewById(R.id.new_banners_cate);
btn_send_ch = (FloatingActionButton) findViewById(R.id.btn_send_ch);
dialog = new ProgressDialog(this);
dialog.setMessage("صبر کن...");
}
}
当发送数据时,在这里输入图像描述
暂无答案!
目前还没有任何答案,快来回答吧!