如何获得最后的自动增量值作为外键到PHP中的另一个表 [英] How to get last auto increment value as foreign key to another table in php

查看:86
本文介绍了如何获得最后的自动增量值作为外键到PHP中的另一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面向对象的php中,如何从一个表获取数据到另一个表的外键,我有两个表称为 users ,其中有两个字段:id和phonenumber。另一个表是个人资料,其中包含ID,用户ID个人资料图像,用户名,商家名称和城镇,其中用户ID是用户表中ID的外键。我希望在用户表中插入电话号码,在个人资料表中获得user_id的外键。请我需要您的帮助,我是oophp的初学者。谢谢任何帮助,将不胜感激

How to get data from one table to the foreign key of another table in object oriented php, i have two table one called users which has two fields : id and phonenumber . another table is profile which has id,user_id profile_image, username, businessname and town where user_id is a foreign key of id in users table . and i wish i insert phone number in users table i get foreign key of user_id in profile table . please i need your help i am a beginer in oophp . Thanks any help will be greatly appreciated

处理所有功能的Dbhandler.php

<?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) {
        $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;
}
?>

以下文件用于调用函数。

The following file is used to call function.

create.php

<?php 
include './DbHandler.php';
$db = new DbHandler();

$response = array();

if ((isset($_POST['profile_image']) && isset($_POST['username']) &&       isset($_POST['businessname']) && isset($_POST['town']))!= '') {
    $profile_image = $_POST['profile_image'];
    $username = $_POST['username'];
    $businessname = $_POST['businessname'];
    $town = $_POST['town'];

    $res = $db->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.";
    } 
} 
?>


推荐答案

这个问题是一个Android 后端php API ,因此要在配置文件表中轻松获取user_id ,我们不需要此功能:

This question is an android backend php API , so to get user_id easily in profile table , we don't need this 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;

}

但是什么我可以做的是在插入用户后在echo或通过json将id和phonenumber与json一起传递给android的界面,并在您得到的参数之中,您可以选择id作为user_id,最后将其设置为textview或texfield,最后将其用作

以下文件是 DbHandler.php ,其中包括所有插入功能在两个表中:

The following file is DbHandler.php which includes all functions of insertion in two tables :

<?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;
}

}
?>

将电话号码插入用户,并使用json插入Echo ID。该文件名为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);
 }
  ?>

Android Java方法,用于获取json传递的参数并将手机插入用户:

     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<String>() {

            @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<String, String> getParams() {

            // Posting parameters to verfication url
            Map<String, String> params = new HashMap<String, String>();
            params.put("phone",phone);
            return params;
        }
        };
 //
 //        // Adding request to request queue
       AppController.getInstance().addToRequestQueue(strReq,  tag_string_req);
    }

使用create.php文件将所有参数插入配置文件: / strong>

Insert all into profile all parameters with create.php file :

<?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.";
} 
} 
?>

这篇关于如何获得最后的自动增量值作为外键到PHP中的另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆