gpt4 book ai didi

php - 尝试连接到我的 SQL 数据库但抛出错误

转载 作者:行者123 更新时间:2023-11-29 23:28:23 27 4
gpt4 key购买 nike

我查看了所有内容,发现{"success":0,"message":"缺少必填字段"},看起来不错,我缺少什么?我正在开发的这个 Android 项目的重点是在应用程序的 EditText 中插入一个电子邮件地址,这将在我的数据库中创建该新用户 + 用户 ID。

创建用户.php

<?php

/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['uid']) && isset($_POST['email'])) {

$uid = $_POST['uid'];
$email = $_POST['email'];

// include db connect class
require_once __DIR__ . '/DB_Connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO USERS(uid, email) VALUES('$uid', '$email')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully created.";

// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";

// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

这是我的 DB_Connect.php

db_connect.php
<?php

/**
* A class file to connect to database
*/
class DB_CONNECT {

// constructor
function __construct() {
// connecting to database
$this->connect();
}

// destructor
function __destruct() {
// closing db connection
$this->close();
}

/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/DB_Config.php';

// Connecting to mysql database
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());

// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

// returing connection cursor
return $con;
}

/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}

}

?>

这是我的登录 Activity 。用户输入他们的电子邮件地址,然后使用该电子邮件地址将该信息发送到数据库并创建用户 ID。

包 com.wny.wecare;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wny.wecare.R;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.wny.wecare.handler.JSONParser;


public class LoginActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputEmail;
Button btnLogin;

// url to create new user
private static String url_create_user = "http://infinitycodeservices.com/create_user.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final int RC_SIGN_IN = 0;

// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;

private boolean mSignInClicked;

private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;

private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;

public static final String TAG = LoginActivity.class.getSimpleName();


private UiLifecycleHelper uiHelper;

private Session.StatusCallback sessionStatusCallback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
uiHelper = new UiLifecycleHelper(this, sessionStatusCallback);
uiHelper.onCreate(savedInstanceState);

// Create Button
btnLogin = (Button) findViewById(R.id.btnEmail);
btnSignIn = (SignInButton) findViewById(R.id.gplus);

// Edit Text
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);


// Button click listeners
btnSignIn.setOnClickListener(this);
btnLogin.setOnClickListener(this);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}

protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}


Session session = Session.getActiveSession();

}


@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}

if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;

if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}

}


private UserInfoChangedCallback createUserInfoChangedCallback() {
return new LoginButton.UserInfoChangedCallback() {
@Override
public void onUserInfoFetched(GraphUser user) {

if (user != null) {


Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
}
};
}




private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// TODO switch by session state
}

public void onActivityResult(int requestCode, int resultCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// The Facebook login flow requires the users to transition out of, and
// back into, this Activity.
// That's why we need the onActiviyResult method :)
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);

if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}

mIntentInProgress = false;

if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

// Get user's information
getProfileInformation();

// Update the UI after signin
updateUI(true);

}



/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);

llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.GONE);
}
}

/**
* Fetching user's information names, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);

txtName.setText(personName);
txtEmail.setText(email);

// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;



} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

/**
* Button on click listener
* */
@Override
public void onClick(View v) {
// creating new user in background thread
new CreateNewUser().execute();
switch (v.getId()) {
case R.id.gplus:
// Signin button clicked
signInWithGplus();
break;


}
}

/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}



/**
* Background Async Task to Create new user
* */
class CreateNewUser extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Logging In..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Creating User
* */
protected String doInBackground(String... args) {
String email = inputEmail.getText().toString();


// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));


// getting JSON Object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);

// check log cat fro response
Log.d("Create Response", json.toString());

// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);

// closing this screen
finish();
} else {
// failed to create user
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}



/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

}

@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
}

@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}

@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()){
Intent i = new Intent(LoginActivity.this,MainActivity.class);
startActivity(i);
}

}
}

最佳答案

所以我无法找出多个错误,因此我使用 GET 采用了不同的路线。还必须更改我的 JSONParcer.java。不抛出任何错误并直接进入 MainActivity 类...但是!此方法将创建一个带有 uid 且没有数据/电子邮件地址的新列

更新create_user.php

<?php



/*

* Following code will get all agencies matching the query

* Returns essential details

* An agency is identified by agency id

*/



require("DB_Link.php");



//query database for matching agency

$query = "INSERT INTO user(Email) VALUES('$email')";



$email = ($_GET['Email']);



//Execute insert query

try {

$stmt = $db->prepare("INSERT INTO user(Email) VALUES('$email')");

$stmt->execute(array('email' => $email));

}

catch (PDOException $ex) {

$response["success"] = 0;

$response["message"] = "Database Error!";

die('Error!: ' . json_encode($ex->getMessage()));;

}

//Execute select query on success

$stmt = $db->prepare("SELECT * FROM user WHERE Email = :email");

$stmt->execute(array('email' => $email));



//Retrieve all found rows and add to array

$result = $stmt->FETCHALL(PDO::FETCH_ASSOC);

echo json_encode($result);


?>

还有我的 LoginActivity.java 的更新

package com.wny.wecare;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.wny.wecare.handler.JSONParser;


public class LoginActivity extends Activity implements OnClickListener {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputEmail;
Button btnLogin;

public String strUid;
// url to create new user
private static String url_create_user = "http://infinitycodeservices.com/create_user.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);

// Edit Text
inputEmail = (EditText) findViewById(R.id.email);


// Create button
Button btnCreateUser = (Button) findViewById(R.id.btnEmail);

// button click event
btnCreateUser.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// creating new user in background thread
new CreateNewUser().execute();
}
});
}

/**
* Background Async Task to Create new User
* */
class CreateNewUser extends AsyncTask<String, String, String> {



/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Logging in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* Creating User
* */
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;

String email = findViewById(R.id.email).toString();

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", strUid));
params.add(new BasicNameValuePair("email", email));

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

Log.d("request!", "starting");
// getting product detail s by making HTTP request
JSONArray json = jParser.getJSONFromUrl(
url_create_user , params);

// check your log for json response
Log.d("Login attempt", json.toString());

// json success tag
// success = json.getInt(TAG_SUCCESS);
// if (success == 1)
{
Log.d("Login Successful!", json.toString());

//SAVE
SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
SharedPreferences.Editor edUi = ui.edit();
edUi.putString("uid", strUid);
edUi.putString("email", email);
edUi.commit();

startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();

// Returns Toast "Login success!"
//return json.getString(TAG_MESSAGE);


}

return null;

}

/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}

}

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

}

}

JSONParcer.java

package com.wny.wecare.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";

public JSONParser() { }

public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
else { Log.e("==>", "Failed to download file");
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray( builder.toString());
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}

关于php - 尝试连接到我的 SQL 数据库但抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com