I can't get the values in the table Accounts to decrement when I try to delete a post. The values I would like to decrement are "PostCount", "Likes Count" and "CommentsCount". Currently only the "PostCount" works.
Please can you tell me what I am doing wrong:
$arg = mysql_query("SELECT `numberOfLikes` FROM Posts WHERE `id` = '$postID'") or die(mysql_error());
$query = mysql_query("SELECT * FROM Likes WHERE `postID` = '$postID'");
while ($row = mysql_fetch_assoc($query)) {
$b = $row['accountID'];
mysql_query("UPDATE Accounts SET `numberOfLikes` = (`numberOfLikes` - 1) WHERE `id` = '$b'");
}
$arg = mysql_query("SELECT `numberOfComments` FROM Posts WHERE `id` = '$postID'");
$query = mysql_query("SELECT * FROM Posts WHERE `id` = '$postID'");
while($row = mysql_fetch_assoc($arg)) {
$b = $row['accountID'];
mysql_query("UPDATE Accounts SET `CommentsCount` = (`CommentsCount` - 1) WHERE `id` = '$b'");
}
$arg = mysql_query("SELECT `PostCount` FROM Accounts WHERE `id` = '$accountID'");
while ($row = mysql_fetch_assoc($arg)) {
mysql_query("UPDATE Accounts SET `PostCount` = (`PostCount` - 1) WHERE `id` = '$accountID'");
}
mysql_query("DELETE FROM Likes WHERE `postID` = '$postID'");
mysql_query("DELETE FROM Comments WHERE `postID` = '$postID'");
mysql_query("DELETE FROM Posts WHERE `id` = '$postID' AND `accountID` = '$accountID'") or die(mysql_error());
exit("Deleted post");
First up looping queries kills your execution time. You want to limit it to as little queries as possible, this is where implode comes into play:
// what is this for? I do not see it being used. $arg = mysql_query("SELECT `numberOfLikes` FROM Posts WHERE `id` = '$postID'") or die(mysql_error());
$query = mysql_query("SELECT * FROM Likes WHERE `postID` = '$postID'");
while ($row = mysql_fetch_assoc($query)) {
$b[] = $row['accountID'];
}
mysql_query("UPDATE Accounts SET `numberOfLikes` = (`numberOfLikes` - 1) WHERE `id` IN(" . implode(',', $b) . ")") or trigger_error('MySQL Update Failed: ' . mysql_error());
This will be much more efficient and have to same effect.
The next query, should be similar:
$arg = mysql_query("SELECT `numberOfComments` FROM Posts WHERE `id` = '$postID'");
// again an extra unnecessary query not being used. $query = mysql_query("SELECT * FROM Posts WHERE `id` = '$postID'");
$b=array();
while($row = mysql_fetch_assoc($arg)) {
$b[] = $row['accountID'];
}
mysql_query("UPDATE Accounts SET `CommentsCount` = (`CommentsCount` - 1) WHERE `id` IN(".implode(',', $b) . ")") or trigger_error(mysql_error());
This next one, I do not even know why you are looping through it:
//$arg = mysql_query("SELECT `PostCount` FROM Accounts WHERE `id` = '$accountID'");
//while ($row = mysql_fetch_assoc($arg)) {
mysql_query("UPDATE Accounts SET `PostCount` = (`PostCount` - 1) WHERE `id` = '$accountID'") or trigger_error(mysql_error());
//}
As you are not utilizing that data anywhere, just run the update query.
Implementing the above should speed up your application and reduce redundancy. implode is very handy and running 1 query vs several is almost always preferred. I am not sure if that will solve your problem, but it is a huge step in the right direction in fixing your code.
I re-coded my if statement containing the code I posted and it is now working perfectly:
mysql_query("UPDATE Accounts SET `PostCount` = (`PostCount` - 1) WHERE `id` = '$accountID'");
$query = mysql_query("SELECT * FROM Likes WHERE `postID` = '$postID'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
$accID = $row['accountID'];
mysql_query("UPDATE Accounts SET `Likes Count` = (`Likes Count` - 1) WHERE `id` = '$accID'");
}
$query = mysql_query("SELECT * FROM Comments WHERE `postID` = '$postID'");
while($row = mysql_fetch_assoc($query)) {
$accID = $row['accountID'];
mysql_query("UPDATE Accounts SET `CommentsCount` = (`CommentsCount` - 1) WHERE `id` = '$accID'");
}
mysql_query("DELETE FROM Likes WHERE `postID` = '$postID'");
mysql_query("DELETE FROM Comments WHERE `postID` = '$postID'");
mysql_query("DELETE FROM Posts WHERE `id` = '$postID' AND `accountID` = '$accountID'") or die(mysql_error());
exit("Deleted post");
Related
Hi guys i'm quite new to PHP but I'm currently working on this site and I want it to check if the total_online_time for the user is 0 or less then it should execute the script which will create a room for the user. However after trying with this script the .php page won't load.
http://pastebin.com/XDLhFvtE
<?php
$getStats = mysql_query("SELECT total_online_time FROM `users` WHERE id = '".$_SESSION['user']['id']."'");
if ($getStats > 0)
$getRoomKit = mysql_fetch_assoc(mysql_query("SELECT * FROM room_starterkit ORDER BY RAND() LIMIT 1"));
$getRoom = mysql_fetch_assoc(mysql_query("SELECT * FROM `rooms` WHERE id = '".$randomRoomID['id']."' LIMIT 1"));
$welcomeMessage = "Welcome " . $_SESSION['user']['username'];
mysql_query("INSERT INTO `rooms` (caption,owner_id,description,model_name,wallpaper,floor) VALUES ('".$welcomeMessage."', '".$_SESSION['user']['id']."', 'Welcome to Hablore', '".$getRoomKit['room_Model']."', '".$getRoomKit['room_Wallpaper']."', '".$getRoomKit['room_Floor']."') ");
$theRoomID = mysql_fetch_assoc(mysql_query("SELECT id FROM `rooms` ORDER BY `id` DESC LIMIT 1"));
mysql_query("UPDATE `users` SET `home_room` = '".$theRoomID['id']."' WHERE `id` = '".$_SESSION['user']['id']."'");
$getRoomItems = mysql_query("SELECT * FROM room_itemkits WHERE roomKit = '".$getRoomKit['id']."'");
while($CurItem = mysql_fetch_assoc($getItems)){
mysql_query("INSERT INTO `items` (user_id, room_id, base_item, extra_data, x, y, z, rot, wall_pos) VALUES ('".$_SESSION['user']['id']."','".$lastRoomID['id']."','".$CurItem['base_item']."','".$CurItem['extra_data']."','".$CurItem['x']."','".$CurItem['y']."','".$CurItem['z']."','".$CurItem['rot']."','".$CurItem['wall_pos']."')");
}
}
?>
Here is what I am trying to do (in pseudo code)
if (dB entry exists) {
UPDATE the dB entry
}else{
UPDATE a default dB entry
}
This is not a "INSERT INTO ... ON DUPLICATE" question.
I'm hoping there is some kind of UPDATE ... ON DUPLICATE type of slick code to do this in one line.
My code creates $userName from the $_GET['U'] request. If $userName exists in the database (it's a unique key), then increment a counter in the database. Else, increment a counter for a default entry.
Here is my current code to update the counter:
$userName = $_GET['U'];
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '" . $userName . "'";
mysqli_query($conn,$sql);
And if this particular username doesn't exist, I want this to happen:
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = 'default'";
mysqli_query($conn,$sql);
Are you looking for this,
$userName = $_GET['U'];
$query_uname_exists = "SELECT count(*) FROM stats WHERE `userName` = '" . $userName . "'";
$uname_count = mysqli_query($conn,$query_uname_exists);
if($uname_count > 0){
#update
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '" . $userName . "'";
mysqli_query($conn,$sql);
}
else{
#update default
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = 'default'";
mysqli_query($conn,$sql);
}
Use the following query
$sql = "Update stats SET count = count + 1 where username = (case when username= ". $userName ". then username else 'default' end)";
This is the most I can shrink it for you:
$userName = mysqli_query($conn, "SELECT count(*) FROM stats WHERE `userName` = '".$_GET['U']."' LIMIT 1") == 0 ? 'default' : $_GET['U'];
mysqli_query($conn, "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '".$userName."' LIMIT 1");
I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.
SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5
The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.
You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}
This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5
Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5
You're changing the value of $result in your loop. Change your second query to use a different variable.
it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
If i'm doing multiple mysql queries on the same table, occasionally some get skipped.
Why is that?
For example:
<?php
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
?>
Sometimes one of the queries will not be executed?
Why is that?
-Or is it something wrong with my server not general mysql?
(Obviously I know now to update the same table in the same query, but before that I was very confused as to why it happens, can anyone please explain?)
Thanks!
You do not need to make 3 queries, if you are updating the same rows:
$q = "
UPDATE table
SET field = '',
field2 = '',
field3 = 0
WHERE Id = :id
";
$statement = $pdo->prepare( $q );
$statement->bindParam(':id', $something, PDO::PARAM_INT);
$statement->execute();
Also, you should stop using the ancient mysql_* functions. They are not maintained anymore and process for deprecation has already begun.
Maybe you should avoid the 10+ year old API and learn something for this decade: PDO Tutorial for MySQL Developers.
debug your code to see if a query fails:
$result = mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Use the following to debug the code:
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'") or die(mysql_error());
UPDATE
Make sure you are escaping $something using:
$something = mysql_real_escape_string($something);
I am deleting a row (user) from the table Accounts and I am trying to set the values "Following Count" and "Follower Count" to their value with one subtracted. But for some reason that does not happen. The account deletes successfully, but the decrement doesn't happen.
Please can you tell me what I am doing wrong:
$query = mysql_query("SELECT * FROM `Accounts` WHERE `Username` = '$username' AND `Password` = '$password' AND `Email Address` = '$emailAdd'");
if (mysql_num_rows($query) < 1) {
exit("Account doesn't exist");
}
$row = mysql_fetch_assoc($query);
$id = $row["id"];
$query = NULL;
mysql_query("DELETE FROM `Comments` WHERE `accountID` = '$id'");
mysql_query("DELETE FROM `Likes` WHERE `accountID` = '$id'");
mysql_query("DELETE FROM `Posts` WHERE `accountID` = '$id'");
mysql_query("DELETE FROM `Accounts` WHERE `id` = '$id'");
$arg = mysql_query("SELECT * FROM Following WHERE followingUserID = '$id'");
if (mysql_num_rows($arg) >= 1) {
for ($i = 0; $i < mysql_num_rows($arg); $i++) {
$arr = mysql_fetch_assoc($arg);
$followingUserID = $arr['followingUserID'];
$followedUserID = $arr['followedUserID'];
$art = mysql_fetch_assoc(mysql_query("SELECT `Following Count` FROM Accounts WHERE `id` = '$followedUserID'"));
$followingCount = $art['Following Count'];
$followingCount = $followingCount-1;
$arts = mysql_fetch_assoc(mysql_query("SELECT `Follower Count` FROM Accounts WHERE `id` = '$followingUserID'"));
$followedCount = $arts['Followed Count'];
$followedCount = $followedCount-1;
mysql_query("UPDATE Accounts SET `Following Count` = '$followingCount' WHERE `id` = '$followingUserID'");
mysql_query("UPDATE Accounts SET `Follower Count` = '$followedCount' WHERE `id` = '$followedUserID'");
mysql_query("DELETE FROM Following WHERE followingUserID = '$id'");
}
}
exit("Closed");
Why not simply do
mysql_query("UPDATE Accounts SET `Following Count` = (`Following Count` - 1) WHERE `id` = '$followingUserID'");
mysql_query("UPDATE Accounts SET `Follower Count` = (`Following Count` - 1) WHERE `id` = '$followedUserID'");
this way you wont need the 2 selects.