Reputation: 11
I'm making a simple webshop for my university project that uses two tables from database (users and items). I try to insert into the database some information about the specific item. The last column is the id of the logged user. I make query that receiving from 'users' table the id of the actually logged user. When I use this variable ($lastlogin) printing via echo it shows a correct value. Unfortunately when I try to insert the id to the table 'items' with insert query, there goes 0 instead of the correct value (eg. 5). Does anyone know how to fix my problem? I will be grateful.
$idlogin = "SELECT id FROM users WHERE login=:login";
$query = $db->prepare($idlogin);
$query->bindParam(":login", $_SESSION['login']);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$lastlogin = $row["id"];
$sql = "INSERT INTO `items` VALUES (NULL, :name, :description, :cust_id)";
$params = [ ":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => '$lastlogin'];
$query = $db->prepare($sql);
$query->execute($params);
Upvotes: 0
Views: 60
Reputation: 11
Ok, thanks for everyone who tried to help me
I found a clue in Michael Berkowski response at this thread $lastlogin was initialized only the first time, so I put it into $_SESSION['lastlogin'] and call it in sql query.
$idlogin = "SELECT id FROM users WHERE login=:login";
$query = $db->prepare($idlogin);
$query->bindParam(":login", $_SESSION['login']);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$lastlogin = (int)$row["id"];
$_SESSION['lastlogin'] = $lastlogin;
$sql = "INSERT INTO items VALUES (NULL, :name, :description, :cust_id)";
$params = [
":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => $_SESSION['lastlogin']
];
$query = $db->prepare($sql);
$query->execute($params);
Now everything works great. Thanks again for your time.
Upvotes: 0
Reputation: 33186
You don't have to put $lastlogin
between quotes in your params. If you do, mysql will see this as a string with the value "$lastlogin"
. Mysql won't be able to parse this to an integer and add the value 0
instead.
$params = [
":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => $lastlogin
];
Upvotes: 2