2

我是一名 android/java 开发人员,我正在努力使用 php。我已经在数据库中插入了一个新用户,现在我想获取他们的 ID。

我该怎么处理结果?我想将它分配给一个变量。

$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";
$result = 

PS:我用的是mysql,不是mysqli。

编辑:这是我所做的:

$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email ."';";
$store_info = mysql_fetch_array(mysql_query($query)); 
$user_id = $store_info['user_id'];
$response["message"] = "User created with id: " . $user_id;
echo json_encode($response);

在数据库中插入(成功)用户后的错误消息:

null{"success":3,"message":"User created with id: "}
4

5 回答 5

6

我假设您正在使用 MySQLi API

$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query

$store_info = mysqli_fetch_array(mysqli_query($connection, $query)); 
//Execute the query, fetch the result, it's just one result so no need for a while loop

echo $store_info['user_id']; //echo id

根据评论,您请求了一个mysql_()版本,因此您可以...

$query = "SELECT user_id FROM users WHERE user_email = '$user_email'"; //Your Query

$store_info = mysql_fetch_array(mysql_query($query)); 
//Execute the query, fetch the result, it's just one result so no need for a while loop

echo $store_info['user_id']; //echo id

仍然考虑使用mysqli_()PDO代替。为什么?因为mysql_()现在已弃用,请阅读文档页面上的红色框,上面写着...

在此处输入图像描述

请参阅答案以获取 PDO 教程

于 2013-10-31T07:53:10.517 回答
3

这是 PDO 变体:

<?php
//credentials
$host = 'localhost';
$user = "user";
$password = '';
$db_name = 'test';
$port = 3306;

//connection to the database
try
{
    $connection = new PDO("mysql:host=$host;port=$port;dbname=$db_name", $user, $password);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}

//prepare and execute SELECT statement
$sth = $connection->prepare("SELECT user_id FROM users WHERE user_email = :email");
$sth->execute(array(':email' => $user_email));

$record = $sth->fetch(PDO::FETCH_ASSOC);
print $record["user_id"];
于 2013-10-31T07:59:11.890 回答
0

如果你使用 mysql(但你不应该,它已被弃用):

$result = mysql_query("SELECT user_id FROM users WHERE user_email = '$user_email'");
$row = mysql_fetch_row($result);

echo $row[0]; // you result (id)
于 2013-10-31T08:00:04.180 回答
0

您的错误来自 SQL 查询中的错误:您使用=了两次运算符:

$query = "SELECT user_id FROM users WHERE user_email = = '" . $user_email . "'";

一定是:

$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";
于 2013-10-31T08:04:25.710 回答
0

联系:

define("HOST","localhost");
define("USER","mysql_username");
define("PASS","password");

$conn = mysql_connect(HOST,USER,PASS) or die("<h3>Sorry, could not connect to MySQL. Please Try Again</h3>");
$db = mysql_select_db(DBNAME,$conn) or die("<h3>Sorry, could not connect to Database. Please Try Again</h3>")

询问:

$query = "SELECT user_id FROM users WHERE user_email = = '" . $user_email . "'";
$result = mysql_query($query);
$row=mysql_fetch_assoc($result);
于 2013-10-31T08:03:35.203 回答