【发布时间】:2014-04-04 16:58:44
【问题描述】:
我正在使用 php 和 mysql 数据库来做一些插入。 我有 2 张桌子。
- 用户
- 状态 其中第二个表作为外键 user_id 在这两个表之间关联
我的问题是,当我插入状态表时,无论 user_id 是什么,user_id 字段都会更改并取 0。
那么如何解决这个问题???
这是 login.php 的代码
<?php
//array for JSON response
$response = array();
// check for required fields
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$sql = mysql_query("Select user, password from users where user='$user'")or die(mysql_error());
$count_query = mysql_num_rows($sql);
if($count_query >0){
$response["success"] = 1;
$response["message"] = "correct Informations";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Wrong User Or Pass";
// 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);
}
?>
status.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "You must Write something";
// echoing JSON response
die (json_encode($response));
}
// check for required fields
else if (isset($_POST['status'])) {
$status = $_POST['status'];
// 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 status(status, user_id) VALUES('$status' , '$last_insert_id')") or die(mysql_error);
$last_insert_id = mysql_insert_id();
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Your Status has been saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
die (json_encode($response));
}
}
?>
我在 android 上使用 php,所以它们不是 html 形式
【问题讨论】:
-
在调用 mysql_query() 之前,您的 '$last_insert_id' 未设置为任何值?
-
那么如何解决这个问题并获取添加到数据库中的user_id字段的值???
-
如果这是关于登录,您可以将用户 ID 放在 cookie 中,这样您就可以在应用程序的任何地方使用它
-
如何将用户ID放入cookie并在android中使用??
-
我不熟悉在 Android 中运行 PHP,但我想您应该能够创建某种会话,正如 @Marc B 在他的回答中所说。这就是我所说的使用 cookie 的意思。
标签: php mysql sql-insert