I'm trying to update the selected random row in database here is my php code
$offset_result = mysqli_query($conn, "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `tbl_combi` WHERE `clear` = 0 ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysqli_query($conn, "SELECT * FROM `tbl_combi` LIMIT $offset, 1");
$result_fetch = mysqli_fetch_array($result);
echo $result_fetch[1];
You never perform any update. Here is something you could try (it might need some tuning to fit your need) :
$offset_result = mysqli_query($conn, "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `tbl_combi` WHERE `clear` = 0 ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$updateSql = 'UPDATE tbl_combi SET my_field="my_value" WHERE offset=' . $offset;
mysqli_query($conn, $updateSql);
$result = mysqli_query($conn, "SELECT * FROM `tbl_combi` LIMIT $offset, 1");
$result_fetch = mysqli_fetch_array($result);
echo $result_fetch[1];
Related
How do I count number of results with limits? Obviously the code I have is not correct. Any help?
$result = mysqli_query ($conn, "select SQL_CALC_FOUND_ROWS * from $sql $limit");
$db_count = mysqli_query ("SELECT FOUND_ROWS()");
ANSWER: $sql = "$db_name.$db_table $where $where_search $db_sort";
$result = mysqli_query ($conn, "select * from $sql $limit");
$rec = mysqli_fetch_array(mysqli_query($conn, "SELECT COUNT(*) as totalCount FROM $sql"));
$db_count = $rec['totalCount'];
I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>
I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).
I need to generate a random row from my MySql database and i have found example here:
http://akinas.com/pages/en/blog/mysql_random_row/
And i want to use solution 3 which looks like this:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `users` LIMIT $offset, 1 " );
My code looks like this now:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
echo $random_date['user_name']; //display username of random user
But when i refresh the page: approximatly 7 of 10 times nonthing shows up. No username at all and also im trying to print out the id of the user but it's also empty.
It seems that it's not getting anything at all from the database when refreshing and sometimes it get's data from the database. Any idea why this might happen?
In this particular case, the problem is that you're working with two different queries; the first query is:
SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users`
Whereas the second one includes a condition:
SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1
^^^^^^^^^^^^^^^^^^^^^^^
Both queries should operate over the same result set.
Its because in your first query you dont have a where, but in the second query you do.
if you have 50 rows and only 15 with profile_image = 2 That will be the reason why most appear as nothing.
Your query becomes LIMIT 30,1 when there are only 15 results for example
Make sure the same where is used in both queries.
Also avoid using mysql_* functions in new code
The solution for my problem was this, BIG thanks to: #Jack
This query will find random row in a mysql table very fast.
$gender_search = $logged_in_user['gender_search'];
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image='2' AND gender='$gender_search'");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' AND gender='$gender_search' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
I have now converted this string to PDO if someone needs it.
$statement = $dbConn->prepare("SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image=? AND gender=?");
$statement->execute(array('2',$logged_in_user['gender_search']));
$offset_row = $statement->fetch(PDO::FETCH_OBJ);
$offset = $offset_row->offset;
$statement2 = $dbConn->prepare("SELECT * FROM `users` WHERE profile_image=? AND gender=? LIMIT ?, 1");
$statement2->execute(array('2', $logged_in_user['gender_search'], $offset));
$random_date = $statement2->fetch(PDO::FETCH_BOTH);
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");