This is an elementary question, I know, however I can't seem to crack it with my code.
I have my login session username assigned to $username - which inserts perfectly, however, I want $id to be assigned the user ID which is located in the 'users' table.
I currently have 2 tables, users and trips.
Users has the following columns:
id (PK,AI),
username,
email,
password,
trn_date
Trips has the following columns:
id (PK,AI),
user (FK_users.ID),
name,
from,
to, date, space, email, telephone, comments
Here is my code:
<?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();
?>