我是一名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);
将用户插入(成功)到db:
后的错误消息null{"success":3,"message":"User created with id: "}
答案 0 :(得分: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教程的this答案
答案 1 :(得分: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"];
答案 2 :(得分: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)
答案 3 :(得分: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);
答案 4 :(得分:0)
您的错误是由于SQL查询中的错误引起的:您使用了=
运算符两次:
$query = "SELECT user_id FROM users WHERE user_email = = '" . $user_email . "'";
必须:
$query = "SELECT user_id FROM users WHERE user_email = '" . $user_email . "'";