-1

I have to insert the values of a donation form into a table. The table has a foreign key 'uid' which is the donor's id. When I tried to insert the data without giving value to foreign key, the insertion failed. Then I set the FK value to null. In this case the data was inserted into the table but the value of 'uid' (FK) was null obviously. Now how do I insert the correct value? The correct value whould be the uid of the donor who is currently logged in.

<?php

if (!isset($_SERVER['HTTP_REFERER'])) {
    header('location:index.php');
    exit;
}

include 'header.php';
session_start();
$servername = "localhost";
$username = "root";
$password = "sql";
$db = "sp";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
if ($_POST) {
    $item = $_POST['item'];
    $details = $_POST['details'];
    $quantity = $_POST['quantity'];

    $sql = "INSERT INTO donation (item, details, quantity) VALUES ('$item', '$details','$quantity');";

    if ($conn->query($sql) == true) {
        echo "Successful submission";
    } else {
        echo $sql;
    }
    $conn->close();
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • It is a very bad idea to use `die(mysqli_error($conn));` or display mysqli error messages in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 20 '20 at 23:13

1 Answers1

-1

The login form should put the user's UID in a session variable. Then you can use that in the INSERT query.

You should also use a prepared statement to prevent SQL injection.

$stmt = $conn->prepare("INSERT INTO donation (uid, item, details, quantity) VALUES (?, ?, ?, ?);");
$stmt->bind_param("iisi", $_SESSION['uid'], $item, $details, $quantity);
if ($stmt->execute()) {
    echo "Successful submission";
} else {
    echo "Error: $stmt->error";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612