我正在使用PDO
将数据保存到数据库,但似乎没有保存数据,即使它不会引发错误。
我正在使用Android的OKhttp3
类将POST
个请求发送到名为chatroom.php
的PHP文件。
<?PHP
include("PDOConnection.php");
//Define some value
define("ACTION_ADD_ROOM","addRoom");
define("ACTION_SELECT","select");
define("RESULT_SUCCESS",0);
define("RESULT_ERROR",1);
define("RESULT_ROOM_EXISTS",2);
$action=$_POST["action"];
$result=RESULT_ERROR;
if(isset($action))
{
if($action==ACTION_ADD_ROOM)
{
$name=$_POST["name"];
$chatdesc=$_POST["chatdesc"];
if(isset($_FILES['chatImage']))
$image=$_FILES['chatImage']['name'];
}
else if($action==ACTION_SELECT)
{
$Id=$_POST["id"];
}
if(ACTION_ADD_ROOM==$action )
{
//check exists Room
if(isExistRoom($cnn,$name))
{
$result=RESULT_ROOM_EXISTS;
}
else
{
insertChatroom($cnn,$name,$chatdesc,$image);
$result=RESULT_SUCCESS;
}
}
else if(ACTION_SELECT==$action)
{
if(login($cnn,$Id))
{
$result=RESULT_SUCCESS;
//login success
}
else
{
//login fail
$result=RESULT_ERROR;
}
}
if((isset($_FILES['chatImage']) && $result==RESULT_SUCCESS && ACTION_ADD_ROOM==$action))
{
$errors= array();
$file_name = $_FILES['chatImage']['name'];
$file_size =$_FILES['chatImage']['size'];
$file_tmp =$_FILES['chatImage']['tmp_name'];
$file_type=$_FILES['chatImage']['type'];
$expensions= array("jpeg","jpg","png");
if(empty($errors)==true)
{
$id=returnID($cnn,$name);
if(!is_dir("uploads/Rooms/".$id))
mkdir("uploads/Rooms/".$id, 0700);
move_uploaded_file($file_tmp,"uploads/Rooms/".$id."/".$file_name);
}else{
print_r($errors);
}
}
}
echo $result;
function insertChatroom($cnn,$name,$chatdesc,$image)
{
try
{
$query = "INSERT INTO chatroom (name, 'chatdesc', image) VALUES(?, ?, ?)";
$stmt = $cnn->prepare($query);
$stmt->execute([$name, $chatdesc, $image]);
}
catch(\PDOException $e)
{
echo "ERROR " . $e->getMessage();
}
}
function isExistRoom($cnn,$name)
{
$query="SELECT * FROM chatroom WHERE name == ?";
$stmt=$cnn->prepare($query);
$stmt->bindParam(1,$name);
$stmt->execute();
$rowcount=$stmt->rowCount();
//for debug
//var_dump($rowcount);
return $rowcount;
}
function login($cnn,$Email,$Password)
{
return 1;
}
function returnID($cnn,$name)
{
$query="SELECT * FROM chatroom WHERE name = ? ";
$stmt=$cnn->prepare($query);
$stmt->bindParam(1,$name);
$stmt->execute();
$result = $stmt->fetchColumn();
//for debug
//var_dump($rowcount);
return $result;
}
?>
我认为使用HTML页面或Android发送POST
请求之间没有区别,但以防万一,这是我的Android代码:
package com.example.android.chatroom.Activities.RegisterActivity;
import android.content.Context;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.example.android.chatroom.Tags;
import com.example.android.chatroom.chatroom;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ChatroomNetworkCallTask extends AsyncTask<String, Void, String> {
ProgressBar mProgress;
FloatingActionButton btnRegister;
View view;
Context context;
//Activity ReciveActivity;
File imageFile;
chatroom Rooms=new chatroom();
public static String Result;
private static final MediaType MEDIA_TYPE = MediaType.parse("image/*");
private static final String IMGUR_CLIENT_ID = "...";
private OkHttpClient client=new OkHttpClient();
public ChatroomNetworkCallTask(chatroom Rooms, File ImageFile, Context mconext,View view)
{
this.context=mconext;
if(ImageFile!=null) {
this.imageFile = ImageFile;
Log.d("getrealfile:", "NEtwork: " + imageFile.getName() + " And Absolute: " + imageFile.getAbsolutePath());
}else
{
Log.d("getrealfile:","Image not set to update");
}
this.Rooms=Rooms;
this.view=view;
mProgress= Rooms.getPbar();
btnRegister=Rooms.getBtnSend();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(mProgress!=null)
mProgress.setVisibility(View.VISIBLE);
if (btnRegister!=null)
btnRegister.setEnabled(false);
}
@Override
protected String doInBackground(String... params) {
try {
Log.d("FIlePath:",imageFile.getAbsolutePath());
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("action", Rooms.getStatus())
.addFormDataPart("name", Rooms.getChatroomName())
.addFormDataPart("chatdesc", Rooms.getChatroomDesc())
.addFormDataPart("chatImage", "imgRoom.jpg",
RequestBody.create(MEDIA_TYPE, imageFile))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url(Tags.ChatroomAddress)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
Result=response.body().string().toString();
Log.d("resultValue:",Result);
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(Result);
StringBuilder build = new StringBuilder();
while (m.find()) { build.append(m.group()); }
return build.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String o) {
super.onPostExecute(o);
Log.d("valueOfo:",""+o);
String msg = null;
if(o != null && o.trim().matches(".*\\d+.*")){
switch (o.toString().trim().toString().trim()) {
case "0":
msg = "اطلاعات شما با موفقیت ثبت شد";
break;
case "1":
msg = "خطا در ثبت اطلاعات";
break;
default:
msg="خطایی بس ناجوانمردانه";
}
}
Snackbar.make(view, msg != null ? msg : "لطفا مجددا تلاس فرمایید",Snackbar.LENGTH_SHORT).show();
if(mProgress!=null)
mProgress.setVisibility(View.INVISIBLE);
btnRegister.setEnabled(true);
}
}
答案 0 :(得分:1)
首先将$cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
添加到您的代码中,以便PDO
实际抛出异常。然后您将收到错误:
您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在#chat;&#39;,chatdesc&#39;,图像)附近使用正确的语法
这是由查询中的单引号引起的。删除它们,它可能会起作用