Hello i have a posts_comments table in my phpmyadmin,
and i can see that when i loop out the comments and send the notifications to users who commented then am getting the repeated details which is sending duplicate comments instead of one comment per user_id.
$sql = "SELECT * FROM posts_comments WHERE id=?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$_GET['id']);
$rows = $stmt->fetchAll();
foreach($rows as $row){
$commenter_id = $row['user_id'];
//Inserting a notifation to all users who comments
$insert = "INSERT INTO notifications(message,user_id)VALUES(?,?)";
$stmt = $this->connect()->prepare($insert);
$stmt->execute('some has commented on a post you are following', $logged_user);
}
Please help me send only one notification per user in posts_comments
Try using distinct keyword. It will eliminate all the duplicate records and fetching only unique records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Related
I created a matching game and stored it score in the database. So every time a user finishes the game, his score is updated in the database replacing the old score.The problem is, I wanted to add the new score with the old score and save it in a new column. I tried something like the below code:
if(isset($_POST['gamescore'])){
$username=$_SESSION['username'];
$fetch = "SELECT * FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$username=$row['username'];
$gamescore= $_POST['gamescore'];
$updatescore= "UPDATE users SET score='$gamescore' WHERE id = '$id'";
mysqli_query($db, $updatescore);
$addscore= "SELECT sum(score='$gamescore') AS sum_score FROM users WHERE id='$id'";
mysqli_query($db,$addscore);
$finalscore="UPDATE sum_score SET sum_score = sum(score='$gamescore') WHERE id='$id'";
mysqli_query($db,$finalscore);
}
}
when I run the above code, score column gets updated by the new score, each time the player finishes the game but the sum of the old score and new score is not happening, I would appreciate if someone could help me with this problem.
The database table has columns "username", "id" , "password", "score" and "sum_score".
You can do everything in your code with one query. As has been mentioned in the comments, you should use prepared statements to protect yourself from SQL injection. Try something like this:
if (isset($_POST['gamescore'])) {
$sql = "UPDATE users
SET score = ?,
sum_score = sum_score + ?
WHERE username = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("iis", $_POST['gamescore'], $_POST['gamescore'], $_SESSION['username'])l
$stmt->execute();
}
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.
i have to get data from one table from my database, BUT after getting the data, i have to access another table to get more data using the id found in the first query.
Here is my code:
$query = "SELECT id,name,datetime FROM table1 WHERE id=?";
if($stmt=mysqli_prepare($mysqli,$query)){
mysqli_stmt_bind_param($stmt,"i",$_SESSION['id']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$datetime);
while(mysqli_stmt_fetch($stmt)){
$query2 = "SELECT id FROM table2 WHERE id=?";
if($stmt2=mysqli_prepare($mysqli,$query2)){
mysqli_stmt_bind_param($stmt2,"s",$id2);
mysqli_stmt_execute($stmt2);
mysqli_stmt_store_result($stmt2);
$num = mysqli_stmt_num_rows($stmt2);
}
The code does not work, i know i can't do that. I'm new with mysqli, in MySQL it works, but in MySQLi don't.
I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli
At the moment I have a script where I add data to the database.
Once the data is entered I would like to get the get the row straight away.
For example if I have a query like this where I have two seperate:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."'";
$query = $this->db->query($sql);
$sql = "SELECT * FROM table";
$query = $this->db->query($sql);
return $query->db->row;
I want to be able to make get that database row instantly after inserting it. Will I have to make a whole new query or is there a quicker way? I am using OpenCarts API if that helps.
Thanks
Peter
INSERT INTO table (a,b,c) VALUES ('a','b','c');
SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();
PHP:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."';";
$sql .= "SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();"
$query = $this->db->query($sql);
return $query->db->row;