В моем приложении я пытаюсь скопировать аудиофайл на сервер и вставлять его в таблицу базы данных mysql. Проблема в том, что в каждой таблице базы данных создаются две записи, каждая из которых я вставляю. Не уверен, в чем проблема. Незлая помощь. Я вставил соответствующий код ниже.Две записи вставляются с Android -> PHP -> MYSQL
код PHP:
<?php
$audNm=$_GET['audNm'];
// Where the file is going to be placed
$target_path = "/home/xxxxxx/public_html/projects/xxxxxx/androidaudio/";
$audio = $audNm.".3gp";
$target_path = $target_path . $audio ;
mysql_connect("localhost","xxxxxxxxxxxx","xxxxxxx") or die(mysql_error());
mysql_select_db("xxxxxxxxxxxxx") or die(mysql_error());
mysql_query("INSERT INTO audio (audionm) VALUES('".mysql_real_escape_string($audNm)."')");
// Multiple entries are inserted here
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename($_FILES['uploadedfile']['name']).
" has been uploaded";
}
else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename($_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
mysql_close();
?>
Android код:
urlString = "http://xxxxxxxx/projects/xxxx/audioinsert.php?audNm="+audFileNm;
timeout= 7000;
Log.d(Globals.TAG,urlch);
//File upload logic
FileInputStream fileInputStream = new FileInputStream(new File(mAudioFileName));
// open a URL connection to the Servlet
URL url = new URL(urlch); //to change
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + mAudioFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(Globals.TAG,"headers are written");
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
httpclientAudio = new DefaultHttpClient();
httpclientAudio.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout);
httppostAudio = new HttpPost(urlch);
httppostAudio.setEntity(new UrlEncodedFormEntity(nameValuePairs));
responseAudio = httpclientAudio.execute(httppostAudio);
entityAudio = responseAudio.getEntity();
isAudio = entityAudio.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(isAudio));
while ((line = r.readLine()) != null) {
total.append(line);
}
Log.d(Globals.TAG, "File is written");
//These logs are written only once. So am not calling this code twice
fileInputStream.close();
dos.flush();
dos.close();
Log.d(Globals.TAG,"response audio:"+ total);
}
catch (MalformedURLException ex)
{
mResponseAudio=Globals.NULLRESPONSE;
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
mResponseAudio=Globals.NULLRESPONSE;
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
catch (Exception e) {
e.printStackTrace();
mResponseAudio=Globals.NULLRESPONSE;
}
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
Log.d(Globals.TAG,"Server Response"+str);
if (str.contains("has been uploaded")){
mResponseAudio=Globals.GOODRESPONSE;
}
}
inStream.close();
Я не разработчик Android, но ваш код Android 99,5%, вероятно, дважды вызывает URL-адрес веб-сайта, потому что я вижу, что в вашем PHP-скрипте нет цикла, а mysql_query() 'только один раз вызывается. – MonkeyZeus
Спасибо, но инструкции logs из моего кода андроида печатаются только один раз. Поэтому не уверен, что URL-адрес дважды вызывается. Я даже положил тормозные точки в код, чтобы проверить это. – ambit
Можете ли вы добавить столбец MySQL с именем «time_log» с varchar (200) и просто заполнить его «microtime (true)»? Если microtime одинаково для обеих вставок, то в mysql_query есть что-то прикованное. Если микротрещины отличаются, то mysql_query() 'вызывается дважды. '" INSERT INTO audio (audionm, time_log) VALUES ('". Mysql_real_escape_string ($ audNm)."', '".microtime (true)."') "' – MonkeyZeus