Como obter o último valor de incremento automático como chave estrangeira para outra tabela em php

Como obter dados de uma tabela para a chave estrangeira de outra tabela em php orientada a objects, eu tenho dois nomes de tabela chamada que tem dois campos: id e número de telefone. outra tabela é o perfil que tem id, user_id profile_image, nome de usuário, nome da empresa e cidade onde user_id é uma chave estrangeira do id na tabela de usuários. e eu gostaria de inserir o número de telefone na tabela de usuários eu recebo a chave estrangeira do user_id na tabela de perfil. Por favor, eu preciso da sua ajuda, eu sou iniciante no oophp. Obrigado, qualquer ajuda será muito apreciada

Dbhandler.php que lida com todas as funções

conn = $db->connect(); } public function createUser($phone) { $response = array(); // insert query $stmt = $this->conn->prepare("INSERT INTO users(phone) values(?)"); $stmt->bind_param("s",$phone ); $result = $stmt->execute(); $new_profile_id = $stmt->insert_id; $stmt->close(); // Check for successful insertion if ($result) { $profile_result = $this->createProfile_userId($new_profile_id); // User successfully inserted return USER_CREATED_SUCCESSFULLY; } else { // Failed to create user return USER_CREATE_FAILED; } } return $response; } public function createProfile_userId($user_id) { //getUser's FNK $stmt = $this->conn->prepare("DELETE FROM profile where user_id = ?"); $stmt->bind_param("i", $user_id); $stmt->execute(); $result = $stmt->execute(); $stmt->close(); return $result; } public function createProfile($profile_image, $username, $businessname,$town) { $response = array(); $stmt =$this->conn->query("SELECT profile_id FROM profile ORDER BY profile_id ASC") ; $profile_id = 0; while($row = $stmt->fetch_array()){ $profile_id = $row['profile_id']; } $path = "uploads/$profile_id.png"; $actualpath = "https://localhost/GoodPriceApi/uploadImage/$path"; // insert query $stmt = $this->conn->prepare("INSERT INTO profile(profile_image, username, businessname, town) values(?, ?, ?, ?)"); $stmt->bind_param("isss",$profile_image, $username, $businessname, $town); $result = $stmt->execute(); $stmt->close(); // Check for successful insertion if ($result) { file_put_contents($path,base64_decode($image)); // User successfully inserted return USER_CREATED_SUCCESSFULLY; } else { // Failed to create user return USER_CREATE_FAILED; } return $response; } ?> 

O seguinte arquivo é usado para chamar a function.

create.php

 createProfile($profile_image, $username, $businessname,$town); if ($res == USER_CREATED_SUCCESSFULLY) { $response["error"] = false; $response["message"] = "Profile created successfully"; } else if ($res == USER_CREATE_FAILED) { $response["error"] = true; $response["message"] = "Sorry! Error occurred during profile creation."; } } ?> 

Esta questão é uma API do php do back-end do Android , de modo a obter user_id facilmente na tabela de perfil , não precisamos desta function:

  public function createProfile_userId($user_id) { //getUser's FNK $stmt = $this->conn->prepare("DELETE FROM profile where user_id = ?"); $stmt->bind_param("i", $user_id); $stmt->execute(); $result = $stmt->execute(); $stmt->close(); return $result; 

}

Mas o que eu poderia fazer é ecoar ou passar id e phonenumber com json para a interface do android após a inserção aos usuários e entre os parâmetros que você obteve, você poderia escolher o id como user_id e, finalmente, configurá-lo para o textview ou texfield e, finalmente, usar como input para ser inserida na tabela de perfil.

O seguinte arquivo é DbHandler.php que inclui todas as funções de inserção em duas tabelas:

 < ?php class DbHandler { private $conn; function __construct() { require_once dirname(__FILE__) . '/DbConnect.php'; // opening db connection $db = new DbConnect(); $this->conn = $db->connect(); } public function createUser($phone) { // insert query $stmt = $this->conn->prepare("INSERT INTO users(phone) values(?)"); $stmt->bind_param("s",$phone ); $result = $stmt->execute(); $stmt->close(); // Check for successful insertion if ($result) { // User successfully inserted return $result; } else { // Failed to create user return NULL; } } } public function createProfile($user_id $profile_image, $username, $businessname,$town) { $stmt =$this->conn->query("SELECT profile_id FROM profile ORDER BY profile_id ASC") ; $profile_id = 0; while($row = $stmt->fetch_array()){ $profile_id = $row['profile_id']; } $path = "uploads/$profile_id.png"; $actualpath = "https://localhost/GoodPriceApi/uploadImage/$path"; // insert query $stmt = $this->conn->prepare("INSERT INTO profile(user_id, profile_image, username, businessname, town) values(?, ?, ?, ?, ?)"); $stmt->bind_param("issss",$user_id, $profile_image, $username, $businessname, $town); $result = $stmt->execute(); $stmt->close(); // Check for successful insertion if ($result) { file_put_contents($path,base64_decode($image)); // User successfully inserted return $result; } else { // Failed to create user return NULL; } 

}?>

Insira o número de telefone em usuários e Echo id com json. o arquivo é chamado NewUser.php:

  < ?php include './DbHandler.php'; $db = new DBHandler(); / json response array $response = array("error" => FALSE); if (isset($_POST['phone'])) { // receiving the post params $phone = $_POST['phone']; // get the user by phone $user = $db->createUser($phone); if ($user != false) { // use is found $response["error"] = FALSE; // $response["uid"] = $user["unique_id"]; $response["user"]["id"] = $user["id"]; $response["user"]["phone"] = $user["phone"]; echo json_encode($response); } else { // user is not found with the credentials $response["error"] = TRUE; $response["error_msg"] = "Sorry we could not find you "; echo json_encode($response); } } else { // required post params is missing $response["error"] = TRUE; $response["error_msg"] = "Required parameter phone is missing!"; echo json_encode($response); } ?> 

Método Android Java usado para obter parâmetros aprovados pelo json e inserir o telefone nos usuários:

  private void createuser(final String phone) { // Tag used to cancel the request String tag_string_req = "req_Verfication"; StringRequest strReq = new StringRequest(Request.Method.POST, Urls."127.0.0.1/myproject/NewUser.php", new Response.Listener() { @Override public void onResponse(String response) { Log.d(TAG, "cerfication Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); // Check for error node in json if (!error) { JSONObject user = jObj.getJSONObject("user"); String phone = user.getString("phone"); String id = user.getString("id"); // pass id to another activity so that will be used as user_id // abfter being set on textView or on textfield and //you hide it on interface then you convert it toString as user_id // finally you insert it in profile table with other parameters // for more details send me email on : mugwales@gmail.com Intent i = new Intent(createuserAccount.this, createuserprofile.class); i.putExtra("id", id); startActivity(i); finish(); } } else { // Error in verfication error message String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Verfication error Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map getParams() { // Posting parameters to verfication url Map params = new HashMap(); params.put("phone",phone); return params; } }; // // // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } 

Insira tudo no perfil de todos os parâmetros com o arquivo create.php:

 < ?php include './DbHandler.php'; $db = new DbHandler(); $response = array(); if ((isset($_POST['user_id']) && (isset($_POST['profile_image']) && isset($_POST['username']) && isset($_POST['businessname']) && isset($_POST['town']))!= '') { $user_id= $_POST['user_id']; $profile_image = $_POST['profile_image']; $username = $_POST['username']; $businessname = $_POST['businessname']; $town = $_POST['town']; $res = $db->createProfile($user_id, $profile_image, $username, $businessname,$town); if ($res == USER_CREATED_SUCCESSFULLY) { $response["error"] = false; $response["message"] = "Profile created successfully"; } else if ($res == USER_CREATE_FAILED) { $response["error"] = true; $response["message"] = "Sorry! Error occurred during profile creation."; } } ?>