How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.
Related
Hoping someone can shed light on this. I am trying to pull the value from 2 fields from a row and based on the row being expired, exclude those 2 values from a drop down list.
I have a table (schedule)
gameID
homeID
visitorID
gameTimeEastern
weekNum
each week there are matchups where 2 teams play each other. Those 2 teams are in a row based on gameID with a specific start time (gameTimeEastern).
I have a function that determines when the matchup is locked, meaning the game has started:
function gameIsLocked($gameID) {
//find out if a game is locked
global $mysqli, $cutoffDateTime;
$sql = "select (DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > gameTimeEastern or DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > '" . $cutoffDateTime . "') as expired from " . DB_PREFIX . "schedule where gameID = " . $gameID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
return $row['expired'];
}
$query->free;
die('Error getting game locked status: ' . $mysqli->error);
This basically determines if the row is expired (gameTimeEastern has passed). I then have a drop down on a form that has a list of all the teams from each matchup for that week.If the row is expired, then I do not want to include the homeID or visitorID from that row in the drop down.
On my page I am trying to show those teams from the expired row but it is failing as the page stops processing when it hit this:
//get expired teams
$expiredGames =gameIsLocked(gameID);
// echo 'Expired games are GAME ' . $expiredGames . '<br>';
for ($eti=1; $eti<=$gameID; $eti++)
{
if ($gameID[$eti]>''){
$sql = "select * from " . DB_PREFIX . "schedule WHERE gameID = '" . $gameID[$eti] . "';";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$result = $query->fetch_assoc();
$expiredHomeTeam = $result['homeID'];
$expiredVisitorTeam = $result['visitorID'];
}
}
echo 'Expired teams for GAME '.$gameID.' are '.$expiredHomeTeam.' and '.$expiredVisitorTeam.'<br>';
}
NEW CODE - Actually giving me the first result
//get expired teams
$expiredGames =gameIsLocked(gameID);
$sql = "select * from " . DB_PREFIX . "schedule WHERE weekNum = '6';";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$result = $query->fetch_assoc();
$expiredHomeTeam = $result['homeID'];
$expiredVisitorTeam = $result['visitorID'];
}
echo 'Expired teams for GAME ' . $expiredGames . ' are '.$expiredHomeTeam.' and '.$expiredVisitorTeam.'<br>';
Ended up using the SQL query to schedule to get results I needed. Thanks for the direction. The logic was already there, just needed to add an if statement to how I populated the array for teams in the drop down.
So I have this table 'users_photos'. It contains 38k rows with user pictures. Every row contains id, userid and link to the photo. So if a user have 3 pictures, that user id will show in 3 rows in the database.
What I want to do is count the number of users with 1 picture in the database, 2 pictures in the database etc.
UPDATE: I have now the following code
$sql = $mysqli->query("SELECT count(*), count_users from (SELECT u_id, count(*) as count_users FROM users_photos group by u_id) temp group by count_users");
$sql->data_seek(0);
while ($row = $sql->fetch_assoc()) {
echo "".$fetch." = " . $row['count_users'] . "\n<br>";
}
This prints the users that have 1 picture and up to 8. Not how many but only shows that in the database there is users that have 1 picture, 2 pictures etc. Now I need to figure out how to print the total users that have 1 picture etc.
Anyone have any tips? thanks on behalf!
Update Your Query With This
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
Sql Query:
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
You Can Print like this
// After Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - count_users" . $row["count_users"]. "<br>";
}
} else {
echo "0 results";
}
You can do something like this:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$sql = 'SELECT u_id, count(*) AS count_users FROM users_photos GROUP BY u_id';
$result = mysqli_query($con, $sql);
while ($row=mysqli_fetch_assoc($result)) {
echo 'User id: ' . $row['u_id'] . ' Count: ' . $row['count_users'] . '<br>';
}
Keep in mind this is just a basic example. In a real world application there is more to do such as checking for errors.
I was wondering how to fetch data of a person from a table. I found the query to LIMIT data fetch from table. Here is what I got so far:
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
It returns data when LIMIT is available but if the LIMIT exceed the entire data returns null. So how can I know if ROW is available or not in table?
use mysql Count
SELECT count(username) FROM users WHERE username ='xyz'
And your $last_limt is not grater than total count-1
You have to check number of rows of the result from that query before proceeding
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
$rowcount=mysql_num_rows($result);
if($rowcount > 0)
{
//next operations
}
else
{
//No more data
}
I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ
I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO