Deleting a row with inner join - php

I've created two tables, simplecomments and commentors, and connected them with INNER JOIN.
Simplecomments is details of each and every commenter, involving their comment, reg_date, commentorid etc...
Commentors is the personal info of a commenter with following columns: id, name, email..
I've joined them successfully, however I'm finding it hard to delete from the joined table.
I want to make it like this logic:
If there's last row of a commentor called --let's say A-- then delete both his/her comment details and A himself/herself from the table.
Else if A has commented plenty of times, with different comments, delete his/her comment details, but let his/her personal info remain since A has other comments there.
This is how I've made it:
if (!empty($_POST["delete"]))
{
foreach ($_POST["delete"] as $key => $value)
{
$resultid = $conn->query("SELECT commentorid FROM `simplecomments` WHERE id=".$value);
$rowid = $resultid->fetch_assoc();
$outputdelete = $rowid["name"] . " has been deleted" . "<br>";
$deletedname = $deletedname.$outputdelete;
$RES = mysql_num_rows($resultid);
$counter = 0;
while($row = $RES)
{
//IF IT'S LAST ROW, DELETE COMMENTOR AND HIS/HER COMMENTDETAILS
if(++$counter == $results) {
$resultid = $conn->query("DELETE FROM `commentor`");
}
//ELSE JUST DELETE HIS/HER COMMENTDETAILS, LET HIS/HER INFO REMAIN
else{
$resultid = $conn->query("DELETE FROM `simplecomments` WHERE id=".$value);
}
}
}
}
However code won't work. I get an error:
Warning: mysql_num_rows() expects parameter 1 to be resource [..]...

Consider running DELETE...INNER JOIN and DELETE with subquery conditionals and avoid PHP query fetch looping with if/else as the logic seems to be the following:
delete any commentor's profile and comments if he/she has only one comment
delete only commentor's comments if he/she has multiple (i.e., more than one) comments.
And yes, all three DELETE can be run at same time across all ids since mutually exclusive conditions are placed between the first two and last one. Therefore, either first two affects rows or last one affects rows per iteration. The unaffected one(s) will delete zero rows from either table.
Also, simplecomments records are deleted first since this table may have a foreign key constraint with commentor due to its one-to-many relationship. Finally, below assumes comment ids are passed into loop (not commentor id).
PHP (using parameterization, assuming $conn is a mysqli connection object)
foreach ($_POST["delete"] as $key => $value) {
// DELETE COMMENTS AND THEN PROFILE FOR COMMENTORS WITH ONE POST
$sql = "DELETE FROM `simplecomments` s
WHERE s.id = ?
AND (SELECT COUNT(*) FROM `simplecomments` sub
WHERE sub.commentorid = s.commentorid) = 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$stmt->close();
$sql = "DELETE c.* FROM `simplecomments` c
INNER JOIN `simplecomments` s ON s.commentorid = c.id
WHERE s.id = ?
AND (SELECT COUNT(*) FROM `simplecomments` sub
WHERE sub.commentorid = s.commentorid) = 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$stmt->close();
// DELETE COMMENTS FOR COMMENTORS WITH MULTIPLE POSTS BUT KEEP PROFILE
$sql = "DELETE FROM `simplecomments` s
WHERE s.id = ?
AND (SELECT COUNT(*) FROM `simplecomments` sub
WHERE sub.commentorid = s.commentorid) > 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$stmt->close();
}
Alternatively, for a DRY-er approach, loop SQL statements in an array:
$sqls = array(
0 => "DELETE FROM `simplecomments` s WHERE s.id = ? AND (SELECT COUNT(*) FROM `simplecomments` sub WHERE sub.commentorid = s.commentorid) = 1",
1 => "DELETE c.* FROM `simplecomments` c INNER JOIN `simplecomments` s ON s.commentorid = c.id WHERE s.id = ? AND (SELECT COUNT(*) FROM `simplecomments` sub WHERE sub.commentorid = s.commentorid) = 1",
2 => "DELETE FROM `simplecomments` s WHERE s.id = ? AND (SELECT COUNT(*) FROM `simplecomments` sub WHERE sub.commentorid = s.commentorid) > 1"
);
foreach ($_POST["delete"] as $key => $value) {
foreach($sqls as $sql) {
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$stmt->close();
}
}

Related

How to count messages for a user with php and mysql

I'm trying to count number of messages each user got. I have a users with user's detail id, name etc. I have created another table users_msgs where I have id, msg_id, user_id. I want to display count of messages each user got. what will be the best way to do it?
The web application have more than 2000 users. so the script have to select all of them and count their messages. I think this is not the best solution.
I thinking of count rows for 1 user from users_msgs table as count and then querying the users table for user's name with his id from users_msgs table.
I have tried selecting all users without any limit:
SELECT * FROM users
then iterating over the results like so:
<?php
while ($user = mysqli_fetch_assoc($users)) {
$count = count_user_msgs($user['id']);
echo "{$user['name']} messages: $count";
}
?>
The count_user_msgs function looks like this:
<?php
$sql = "SELECT COUNT(id) as msgs_count FROM users_msgs WHERE user_id = ?";
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, 's', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_fetch_assoc($result)['msgs_count'];
return $count;
}
return false;
?>
You need to group by each user and get the count:
$sql = "SELECT user_id, name, count(user_id) as msgs_count from table group by (user_id, name)";
$result = $mysqli->query($query)
while ($user = mysqli_fetch_assoc($users)) {
$user_id = $users['user_id'];
$msgs_count= $users['msgs_count'];
$count[$user_id] = $msgs_count;
echo "{$user['name']} messages: $msgs_count";
}
FWIW, You can get it in a single query...
SELECT u.name, count(m.user_id) message_count
FROM users u
LEFT JOIN users_messages m ON u.user_id=m.user_id
GROUP BY m.user_id, u.name
You want to count the number of msg_ids per user_id, so you'll want to GROUP BY user_id and count msg_id, like this:
$sql = "SELECT COUNT(msg_id) as msgs_count FROM user_msgs WHERE user_id = ? GROUP BY user_id";
The GROUP BY might not be necessary.

Get applicants from Table 1 and compare id and get user details from Table 2 Using PHP

Ok so I have two Tables
Applicant list - this shows all applicants
User Table
Now I'm Providing news_id by Post method and I want to list details of all users(email,mobile,username) where the value for user_authToken and user_authtoken is same. Can Someone help me out with this logic using PHP.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile,
FROM appliers_list,user
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();
First of all, your naming is very inconsistent, it's hard to read and understand.
Second, please use prepare statement, otherwise you open your system to SQL injection.
$news_id = $_POST['job_id'];
$stmt = $con->prepare("SELECT email, mobile, user_name
FROM users
WHERE user_authtoken in (select user_authToken from appliers_list where news_id = ?)");
$stmt->bind_param("i", $news_id);
$stmt->execute();
$resultSet = $stmt->get_result();
while($row = $resultSet->fetch_assoc()) {
// data manipulation here
}
you can use left join to get record from both table :
$job_id = !empty($_POST['job_id']) ? intval($_POST['job_id']) : 0;
$resultSet = $con->query("SELECT appliers_list.*,users.email
FROM appliers_list
left join users on appliers_list.user_authToken = users.user_authToken
WHERE news.news_id = '$job_id'
ORDER BY news.id DESC
");
$rows = $resultSet->fetch_assoc();
You didn't specify a relationship between the user and appliers_list tables, so you're getting all rows in user. You also have an extra comma at the end of the SELECT list.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile
FROM appliers_list
JOIN user ON appliers_list.user_authToken = user.user_authToken
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();

Two tables, display multiple results from one matching the ID

I have two tables:
post_languages with the following columns: languageID, languageName
post_to_languages with: postID, postLanguage
What I'm trying to achieve is to display all languages associated with a post.
example: Post 1, languages: French, Russian
Maybe my approach is wrong but this is one of the methods I have tried:
//get language id
$stmt2 = $db->prepare('SELECT languageID FROM post_to_languages WHERE postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
//Count total number of rows
$rowCount2 = $stmt2->rowCount();
if ($rowCount2 > 0) {
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
foreach ($row2 as $langID) {
$stmt3 = $db->prepare('SELECT languageName FROM post_languages WHERE languageID = :languageID');
$stmt3->execute(array(':languageID' => $langID));
$row3 = $stmt3->fetch();
$lang_string = $row3['languageName'];
}
} else {
$lang_string = "Unknown";
}
Doesn't matter what I tried, I get only one language. Maybe I should select post_to_languages by ID first.
You don't need this nested loop, try a join or a subquery. Showing you a subquery. If you have a large number of rows, an inner join will be faster. But a subquery is still heaps faster than a nested loop.
SELECT languageName FROM post_languages WHERE languageID IN
(SELECT languageID FROM post_to_languages WHERE postID = :postID')
If you still don't see any results, replace :postID with a real value and try it in the console.
you are selected different column from diff. table.
in table post_to_language must be same datatype as languageId.
please try this code
//get language id
$stmt2 = $db->prepare('SELECT postLanguage FROM post_to_languages WHERE postID = :postID');
$stmt2->execute(array(':postID'=>$row['postID']));
//Count total number of rows
$rowCount2 = $stmt2->rowCount();
if($rowCount2 > 0){
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
foreach($row2 as $langID) {
$stmt3 = $db->prepare('SELECT languageName FROM post_languages WHERE languageID = :languageID');
$stmt3->execute(array(':languageID'=>$langID));
$row3 = $stmt3->fetch();
$lang_string = $row3['languageName'];
}
} else {
$lang_string = "Unknown";
}
Thank you.

Query inside while loop repeats results from 2 tables

I am not sure if the title expresses the problem accurately or not. Anyways, here is the explanation:
I have 2 tables, the first one holds users IDs, the other one holds their posts.
The fist query selects user IDs from the fist table, and it loop through the second table to find the users (IDs) posts.
The problem is that when the query finds eg. 5 results (user IDs 1, 6, 999.. etc) in the fist table, then it loops 5 times to search in the second table, it shows 5 results even if the real results is 2 post only created by user 1 and 6.
How can I avoid this repeatation?
Here is the code:
$stmt = $conn->prepare('select userid from table where para=?');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$postid= $row2['postid'];
$title= $row2['title'];
}
echo $postid." ".$title."<br>";
}
Try
$qname = "select postid,title from posts as P left join table as T on T.userid=P.uid where where para=?";
Or
You can store the results in a common array during the loop.
like
$tempResult = array();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$tempResult[$userid][] = $row2['postid'];
$tempResult[$userid][] = $row2['title'];
}
}
you can try this query using a JOIN MYSQL.
SELECT u.userid,p.postid,p.title FROM TABLE `user` u
JOIN posts p ON
p.uid = u.userid
WHERE para=?
You can avoid it by only running one query that joins the two tables together. Something like this:
<?php
$stmt = $conn->prepare('select posts.* from table t inner join posts p on t.userid = p.uid where t.para = ? order by uid');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
// $row now has userid, and all post details
}
?>

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

Categories