这是一个基本问题,我知道,但是我似乎无法使用我的代码破解它。
我将我的登录会话用户名分配给$ username - 这完全插入,但是,我希望为$ id分配位于'users'表中的用户ID。
我目前有2张桌子,用户和旅行。
Users
包含以下列:
id (PK,AI),
username,
email,
password,
trn_date
Trips
包含以下列:
id (PK,AI),
user (FK_users.ID),
name,
from,
to, date, space, email, telephone, comments
这是我的代码:
<?php
session_start();
include("auth.php");
include("db.php");
?>
<?php
// SERVER AND DATABASE DETAILS --- WORKING
$servername = "<redacted>";
$username1 = "<redacted>";
$password = "<redacted>";
$dbname = "<redacted>";
//sets session variable username --- WORKING
$username = $_SESSION['username'];
// sets variable to result of sql to determine user_id - NOT WORKING
$id = mysqli_query("SELECT id from `users` where username = '$username'");
// Create connection --- WORKING
$conn = new mysqli($servername, $username1, $password, $dbname);
// Check connection --- WORKING
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert script when adding trip --- WORKING
$sql = "INSERT INTO `trips` (`user`,`name`, `from`, `to`,
`date`, `space`, `email`, `telephone`, `comments`) VALUES ('$id','$username','".$_POST["from"]."','".$_POST["to"]."','".$_POST["datetime"]."','".$_POST["space"]."','".$_POST["email"]."','".$_POST["telephone"]."','".$_POST["comments"]."')";
// Alert pop-up confirming when insert is successful --- WORKING
if ($conn->query($sql) === TRUE) {
echo '<script type="text/javascript">';
echo 'alert("Your trip was successfully added!");';
echo 'window.location.href = "/index.php";';
echo '</script>';
// Error when sql insert fails
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 0 :(得分:0)
替换此行
$id = mysqli_query("SELECT id from `users` where username = '$username'");
用这个
$conn = new mysqli($servername, $username1, $password, $dbname); //since I am not sure where did you initiate the mysqli connection
$res = mysqli_query($conn, "SELECT id from `users` where username = '$username'");
$id = mysqli_fetch_assoc ( $res ) ['id'] ;
我想这会解决你的问题。
mysqli_query
函数不返回您期望的值,而是返回mysqli结果http://php.net/manual/en/mysqli.query.php
因此,您需要先从该对象获取结果,然后从结果中提取值。
在我的示例中,我使用mysqli_fetch_assoc
将数据作为关联数组获取,然后使用['id']
获取特定的列值。