【发布时间】:2016-09-21 14:36:23
【问题描述】:
如何在面向对象的 php 中从一个表获取数据到另一个表的外键,我有两个表,一个名为 users 有两个字段:id 和 phonenumber。另一个表是 profile,它有 id、user_id profile_image、username、businessname 和 town,其中 user_id 是 users 表中 id 的外键。我希望我在用户表中插入电话号码我在配置文件表中获得 user_id 的外键。请我需要你的帮助我是 oophp 的初学者。感谢任何帮助将不胜感激
处理所有功能的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;
}
?>
以下文件用于调用函数。
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.";
}
}
?>
【问题讨论】: