目前,我正在开发一个涉及客户端服务器架构的Android应用程序。据说我必须用PHP编写REST Web服务以进行后端通信。那时我还不知道RESTful架构等等。
在过去的3天里,我学到了很多关于REST
网络服务的知识,并尝试了许多教程。然后,我尝试了一些来自教程和SO的代码。我到目前为止所做的尝试如下:
我有三个php文件,一个名为xyz
的数据库和名为user_accounts
的表,其中包含phpmyadmin中的基本用户详细信息。我在浏览器上安装了高级REST客户端。所有代码都位于名为WWW
的文件夹下WAMP server
的{{1}}目录中。所以,让我展示一些代码:
1。 db_connect.php
my project
在第二个文件中,我有一个名为 <?php
define("SERVER", '127.0.0.1');
define("USER", 'root');
define("PASSWORD", '');
define("DB", 'xyz');
$con = new mysqli(SERVER,USER,PASSWORD,DB);
if ($con->connect_errno){
die("Database Connection Failed");
exit();
}
的函数,用于将用户记录添加到数据库中:
index.php:
adduser
当我使用高级REST客户端测试它时,给出url:
<?php
require_once('db_connect.php');
$response = array();
$result = "";
function adduser($firstname, $lastname, $email, $password) {
global $app;
$req = $app->request();
$firstname= $req->params['firstname'];
$lastname= $req->params['lastname'];
$email = $req->params['email'];
$password = $req->params['password'];
$stmt = $con->prepare("INSERT INTO user_accounts (first_name,last_name,email,password)VALUES (?,?,?,?)");
$stmt->bind_param('ssss', $firstname, $lastname, $email, $password);
$stmt->execute();
$result = $stmt->close();
}
if($result){
$response["success"] = 1;
$response["message"] = "account successfully created.";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "An error occurred during registration.";
echo json_encode($response);
}
?>
和方法http://127.0.0.1/my project/index.php/adduser
和参数:
POST
它显示以下回复:
firstname=somename&lastname=name&email=a@b.gmail.com&password=101010
我无法确定错误的位置。我是新来的。如果有什么不对,请帮忙。
答案 0 :(得分:1)
你应该试试这个:
$affected_rows = $stmt->rowCount();
然后检查行数是否大于0.
<?php
require_once('db_connect.php');
$response = array();
$result = "";
function adduser($firstname, $lastname, $email, $password) {
global $app;
$req = $app->request();
$firstname= $req->params['firstname'];
$lastname= $req->params['lastname'];
$email = $req->params['email'];
$password = $req->params['password'];
$stmt = $con->prepare("INSERT INTO user_accounts (first_name,last_name,email,password)VALUES (?,?,?,?)");
$stmt->bind_param('ssss', $firstname, $lastname, $email, $password);
$stmt->execute();
return $stmt->rowCount();
}
$adduser = addUser($firstname, $lastname, $email, $password);
if($adduser > 0){
$response["success"] = 1;
$response["message"] = "account successfully created.";
echo json_encode($response);
} else{
$response["success"] = 0;
$response["message"] = "An error occurred during registration.";
echo json_encode($response);
}