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
Related
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
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.
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)
Can someone please help me. I'm trying to create a basic like system by inserting the values into mysql and auto incrementing the number of times the column 'likes' has been updated.
Basically the script will insert where there is not currently any record and update if there is a record.
I am trying to insert 'user_id' as a value, aswell but only the liked_id is being inserted into the table. the 'likes' column is being auto incremented as it should be but i need to find out how i can insert the user_id which is the users session id aswel and this isn't being put in. also i am trying to update the column 'user_id_has_liked' from enum value 0 to 1 as a final result.
can someone please show me where i am going wrong. thanks
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("SELECT * FROM ptb_likes WHERE liked_id ='".$user_to_id."' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE ptb_likes SET likes = likes +1 WHERE liked_id = '".$user_to_id."' ");
$user_to_id = mysql_query("ALTER TABLE likes AUTO_INCREMENT = $id");
}
else
{
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id'].",".$user_to_id."') ");
}
$result1 = mysql_query("UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result)
{
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
As the others said, mysql_* statements are depricated, use mysqli_* statements...
The first issue is the code in the user id insert statement was missing some quotes, it should look like this:
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id']."','".$user_to_id."') ");
The user_id_has_liked query issue could be caused by the enum variable being an integer in mysql. you could also try saving your query to a query variable and passing the variable to your query function for readability...
$query = "UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id'];
$result1 = mysql_query($query) or die(mysql_error());
I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}