Cannot save user ID to database - php

I'm pretty much a novice when it comes to coding, so sorry for lack of knowledge here.
I'm trying to retrive a forigne key attribute from one database table (the user's ID number) so I can then make that id a variable which will be used to save the details into another database table.
From that I can view all of the saved records linked with that user's id when they are logged in.
My problem is with getting the user ID and making it a variable to save into the database, I just can't seem to make it work. The rest of the code works if I remove the user ID but I need that to save into the table.
Here's my code:
require_once( "dbconnect.php" );
try
{
$db = getConnection();
function get_id($db)
{
$username= $_SESSION['username'];
$result = $db->query(
"SELECT userID FROM users where username='$username'");
return $result;
}
$uID = get_id($db);
$userID= $uID->setFetchMode(PDO::FETCH_NUM);
$title = $Result->title;
$desp = $Result->description;
$sql = "INSERT INTO saved (userID, title, desp
VALUES ('$userID', '$title', '$desp')";

The proper way
function get_subid($db,$username)
{
$stm = $db->prepare("SELECT userID FROM users where username=?");
$stm->execute(array($username));
return $stm->fetchColumn();
}
$userID = get_subid($db,$_SESSION['username']);

try removing the quotes around userid variable in your query :
$sql = "INSERT INTO saved (userID, title, desp) VALUES ($userID, '$title', '$desp')";

Try the following:
require_once( "dbconnect.php" );
try {
/** * ** connect using the getConnection function written in myfunctions.php ** */ $db = getConnection();
function get_subid($db) {
$username= $_SESSION['username']; //variable accessed through the function
$query = $db->query("SELECT userID FROM users where username='$username'");
$row = $query->row(); //Get's the first Row
$result = $row->userID; //Get's the field userID of this first row
return $result;
}
$uID = get_subid($db);
$title = $Result->title;
$desp = $Result->description;
// insert into database
$data = array(
'userID' => $uID,
'title' => $title,
'desp' => $desp
);
$db->insert('saved', $data);
This should be what you'd like (see the comments)

Related

Turn SQL value to variable

so I have a database table with some user information, like ID, username, etc. and I have been trying to turn a value, for example, Bob's ID into a variable $id from the table. This is what I have right now:
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
and I need to turn it into a variable, because I am combining everything into a sentence so it could be $username has the id of $id. Thanks
Try like this.use sprintf().The sprintf() function writes a formatted string to a variable.
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID,username FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$sentence = sprintf("%s has the id of %u.",$row['username'],$row['ID']);
echo $sentence;
For more see sprintf

Insert into MYSQL Database WHERE username = :username

So, im struggling with this for 2 days, i havent seen any example on google about that it works, so i guess it doesnt work like this:
$steamusername = "xx";
$uname = $_SESSION['username'];
$sql1 = "INSERT INTO users (steamusername) VALUES ( :steamusername) WHERE :username = username";
$query = $conn->prepare( $sql1 );
$result = $query->execute( array( ':steamusername'=>$steamusername, ':username'=>$uname));
It does not give any errors, but it also does not put it into the database.
I really have no idea how i can make it it goes into the user table, i also tried to update the field:
$sql1 = "UPDATE users SET steamusername = :steamusername WHERE username = :username";
$stmt1 = $conn->prepare($sql1);
$stmt1->bindParam(':username', $uname);
$stmt1->bindValue(':steamusername', $steamusername);
$stmt1->execute();
Does anyone know the solution? Thanks in advance!
INSERT is used to create a new record, what you're looking to do is update a current record. You need to use an UPDATE query, as follows:
$query = $conn->prepare( "UPDATE users SET steamusername = :steamusername WHERE username = :username" );
$query->execute(array( ':steamusername' => $steamusername, ':username' => $uname));
Notice that we pass the parameters to the execute() function as an array.

Saving session value in database using php

I have this
session_start();
if ($_SESSION['email']&&$_SESSION['companyID'])
echo $_SESSION['email']."";
else
die("You must be logged in!");
and now im saving some data in database, and i want to save the companyID aswell by using createUser.php which contain these but its not saving the companyID
$userID=0;
$userRole=$_POST ["role"];
$userEmail = $_POST["userEmail"];
$userPassword = $_POST["userPassword"];
$companyID = $_POST[$_SESSION["companyID"]];
// insertion to user_details table
$sql = "INSERT INTO users (userID, email, password,companyID,roleID) VALUES
('$userID', '$userEmail', '$userPassword','$companyID','$userRole')";
Try replacing this:
$companyID = $_POST[$_SESSION["companyID"]];
For this:
$companyID = $_SESSION["companyID"];

Function/Trigger already in use?

Im having problems getting an update function to work. The function marks badges as seen so that they are hidden from a notification window.
The function is called when the user clicks a button to mark them as seen.
I have two triggers on the table its trying to update which I think may be causing the problem.
The problem is : Can't update table 'users' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Triggers:
Function:
function markAsSeen() {
require "connect.php";
$seen = mysqli_query($connection,"Update userbadges
INNER JOIN users ON users.id = userbadges.user_id
SET seen='1'
WHERE studentid = '".$_SESSION["studentid"]."' && seen=0") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($seen)) {
echo 'Done';
}
}
Is there any way around this?
Your issue is that the update_users_trigger trigger makes changes to the contents of the table users, while the query that is triggering the execution of this trigger also uses the table users.
You will need to adjust your query so that this deadlock doesn't occur. It isn't clear which fields are from each table, but I suspect that in your initial query you need to join on users so that you can query on studentid.
You could create a different function to get the userID that you need something like the following:
require_once "connect.php";
function getUserIDFromStudentID($student_id, mysqli $connection)
{
$query = 'SELECT id FROM users WHERE studentid = ? LIMIT 1';
$stmt = $connection->prepare($query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_object();
$result->free();
if ($record) {
return $record->id;
}
}
function markAsSeen(mysqli $connection) {
$user_id = getUserIDFromStudentID($_SESSION["studentid"], $connection);
if (! $user_id) {
throw new Exception('Unable to get user id');
}
$seen_query = 'UPDATE userbadges SET seen = 1 WHERE user_id = ? and seen = 0';
$stmt = $connection->prepare($seen_query);
// Replace the below s to an i if it's supposed to be an integer
$stmt->bind_param("s", $user_id);
$result = $stmt->execute();
if (! $result) {
die(mysqli_error($connection));
}
echo 'Done';
}
Passing the connection object around rather than requiring a global file to be required every time will allow for more flexibility.

running multiple query's in mysql?

i'm currently running this query to delete messages within a messaging system on my site, when the user hits delete the query runs and updates the table in my database.
deleted_to is updated from '0' to '1'
what i also want to do is capture the user's id and store this in the table under the column 'user_who_deleted'
to do this i am using $_SESSION['user_id'] but am having trouble finding a way to have this inserted into the table.
can someone please show me how to do this. thanks
delete message link code:
<?php $inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set)) { ?>
<div class="message_buttons2">Delete Conversation</div>
query that sets deleted_to from 0 to 1 :
function delete_message_to($message, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_messages
SET deleted_to='1'
WHERE msg_id='1' ";
mysql_query($query, $connection);
}
the delete bit works but i am now trying to insert the users $_SESSION['user_id'] into ptb_messages.user_who_deleted
i want this to run as part of the same query if i can. i've tried something like below but it doesnt do anything
function delete_message_next($message, $user) {
global $connection;
global $_SESSION;
$query = "SELECT user_who_deleted
FROM ptb_messages
SET user_who_deleted =" . $_SESSION['user_id'] . "";
mysql_query($query, $connection);
}
Unless i misunderstand, don't you just want to do this?
$query = '
UPDATE
ptb_messages
SET
deleted_to=1,
user_who_deleted = "'.$_SESSION['user_id'].'"
WHERE
msg_id=1';
Ideally, as mentioned, you want to go to mysqli or PDO, and work with prepared statements:
$query = '
UPDATE
ptb_messages
SET
deleted_to= :setDeleted,
user_who_deleted = :userId
WHERE
msg_id= :msgId';
$stmt = $dbh->prepare($query);
$stmt->bindParam(':setDeleted', 1);
$stmt->bindParam(':userId', $_SESSION['user_id']);
$stmt->bindParam(':msgId', 1);
$stmt->execute();
http://www.php.net/pdo.prepared-statements

Categories