I am trying to create a cron job that will select the sum of points from a transaction table.
Based on the Sum of the points and the employee id I must update the total point table.
I want to make sure that I am using the best method and that this will work.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT ID, SUM(POINTS) as Points, FROM Transactions WHERE Status = 1 Group By ID";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
mysql_query("UPDATE Totals SET Points=" + $row["Points"] + "WHERE ID=" + $row["id"]);
}
mysql_free_result($result);
?>
You can still join tables (and subqueries) on UPDATE statements. Try this one,
UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = 1
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points
Hope this helps.
example of using PDO Extension (Code Snippet).
<?php
$query = "UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = ?
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points";
$iStatus = 1;
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $iStatus);
$stmt->execute();
?>
PDO Manual
PDO PreparedStatement
Why can't you just test the script out out before you run it via a cron job? I can't spot anything that's wrong with the syntax; but then again, I only gave it a quick glance and I don't know what your table structure is like.
If you're looking for the BEST way to do things, then you should looking into using mysqli or PDO instead of the mysql functions. That way, you can make use of prepared statements, which won't be as taxing on your DBMS if you're planning on running multiple queries inside a loop. Prepared statements don't require you to make separate round trips to the server, whereas the old mysql functions do.
Related
First and formost, yes i know PHP5.6 is deprecated version, but i want to stick with it and fully learn PHP for myself, before updating to MySQLi.
I'm trying to make a text based game running MySQL and PHP, and currently trying to create a system that:
1.Gets information from user table, username and total actions done (+)
2.At the certain timestamps save all usernames and actions into separete table (-)
3.Resets actions column to 0 for ALL players. (+/- planning to use a mysql trigger and/or cron-job)
My questions:
2) How would you suggest me to insert usernames into seperate table? (only idea i come up is to explode array somehow get variables and sumbit to mysql, question is how to do so? )
3) regarding this number 3, would you suggest something else then triggers or cron-jobs?
Code example bellow
<?php
include './config/connect-db.php';
$result= mysql_query("SELECT * FROM user WHERE actions > 100 ORDER BY
actions DESC LIMIT 5");
while($row = mysql_fetch_array($result)){
if ($row['u_dmisijos'] >= 100) {
echo '<li>'.$row["u_name"].' ('.$row["actions"].')<br>';
} // if actions
} //while loop
?>
EDIT:
MySQL includes a lot of columns, there are only 2 specific I'm focusing on, u_name (username) and actions (actions).
EDIT2:
What i am expecting on second table: ID (AI), username of player with the most action points, username of player with second action points etc. And Datastamp.
expected SQL
ID, nr1, nr2, nr3, nr4, nr5, Datastamp.
Cheers!
I am not sure this will work or not as I have not tested it. But, I hope you might get a general idea.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT * FROM user WHERE actions > 100 ORDER BY actions DESC LIMIT 5";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$q = "INSERT INTO `new_table` (`u_name`, `actions`) VALUES
($row['u_name'],$row['actions'] )";
mysql_query($q);
}
?>
Regarding resetting all actions to 0 you can create a functions like:
function resetActions(){
//update actions to 0
$q = "UPDATE table_name SET actions = 0";
mysql_query($q);
}
Now, whenever you need to reset it you can call this function. Or you can call this function in cron job as you required.
Hi I am attempting to join two MySQL tables. The tables are as follows:
Table 1
Name: mlb_game_feed
Fields: game_feed_game_id, date, home_team, away_team
Table 2
Name: user_picks
Fields: pick_id, game_feed_game_id_fk, user_id_fk
Here is the sql I've attempted to use to join the two tables:
$sql = "
SELECT game_feed_game_id
, home_team
, away_team
, COUNT(1) as cnt
FROM game_feed_mlb
JOIN user_picks
ON user_picks.game_feed_game_id_fk = game_feed_mlb.game_feed_game_id
Where game_feed_mlb.date = '" . $_SESSION['date']."'
AND user_picks.user_id_fk = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
}
}
My intention is to check if the user has picked a winner (either home_team or away_team) from the mlb_game_feed table and if they have, I will change a link from make_pick to change_pick (with an if($count) statement) on the screen.
However, currently I'm not even getting any data back which means my sql is likely incorrect. Any help would be great! Thanks.
Consider the following suggestions:
Use a LEFT JOIN to return ALL records and a conditional aggregate to count matches in cnt field. Later you can use this cnt to run your update hyperlink in PHP. See if block in fetch loop.
As mentioned, your SQL string that concatenates on line breaks does not leave room before the clauses of SQL: FROM, JOIN, ON, and WHERE.
Use a GROUP BY clause for your aggregate query. Non-aggregated columns must appear in this clause else it is a violation of ANSI SQL. Unfortunately, MySQL allows the ONLY_FULL_GROUP_BY mode off whereas every other RDBMS will correctly throw an error.
Use table aliases for more readable code instead of repeating long name tables.
Pass in $SESSION date as a parameter to prepared statement. See ? placeholder in string.
PHP
$sql = "SELECT g.game_feed_game_id, g.home_team, g.away_team, " .
" SUM(CASE WHEN g.game_feed_game_id IS NOT NULL " .
" THEN 1 ELSE 0 END) as cnt " .
"FROM game_feed_mlb g " .
"LEFT JOIN user_picks u " .
" ON u.game_feed_game_id_fk = g.game_feed_game_id " .
"WHERE g.`date` = ? AND u.user_id_fk = 1 " .
"GROUP BY g.game_feed_game_id, g.home_team, g.away_team;"
// CONFIGURE PREPARED STATEMENT AND BIND PARAMETER
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_SESSION['date']);
// EXECUTE STATEMENT AND RETURN RESULTS
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
if($row['cnt'] > 1) {
// change links accordingly...
}
}
}
I made the following code to try and grab the number of entries in 3 tables in a database. The queries work when I use them in phpMyAdmin but when I run this code I get:
Error creating SQL statement
which is generated by the if(!$stmt) statement and I have no idea why it's not working. Thanks in advance :)
<?php
include 'connection.php';
$countArtists = $countAlbums = $countTracks = 0;
/* Create queries to get counts from each table */
$sql = "SELECT COUNT(*) FROM artist;";
$sql .= "SELECT COUNT(*) FROM cd;";
$sql .= "SELECT COUNT(*) FROM tracks;";
$stmt = $conn->prepare($sql);
if(!$stmt)
{
echo "Error creating SQL statement";
return 1;
}
$stmt->execute();
$stmt->bind_result($countArtists, $countAlbums, $countTracks);
echo "<li>Number of Artists: $countArtists</li><br>\n" .
"<li>Number of Albums: $countAlbums</li><br>\n" .
"<li>Number of Tracks: $countTracks</li><br>\n";
?>
I think you want a single query like this:
$sql = "SELECT (SELECT COUNT(*) FROM artist) as countArtists, ".
"(SELECT COUNT(*) FROM cd) as countAlbums, ".
"(SELECT COUNT(*) FROM tracks) as countTracks";
This is one query with three columns, as opposed to three separate queries.
I have a simple function that returns a count from a database table, based on some criteria.
function MyCount($strTable, $strCriteria) {
$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";
if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;
$results = mysql_query($strSQL, $objConn);
$row = mysql_fetch_array($results);
return $row[0];
}
Its very useful for quickly getting a value in 1 line of code, e.g:
$Users = MyCount("Users", "Deleted = 0");
However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");
$objQuery->bindParam(':table_name', $strTable);
$objQuery->bindParam(':criteria', $strCriteria);
I guess the obvious would be:
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");
$objQuery->bindParam(':table_name', $strTable);
But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?
Thanks
This line is the issue:
$objQuery->bindParam(':table_name', $strTable);
You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.
So you just build the query manually:
SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria
function my_count($strTable, $strCriteria, $objConn)
{
$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";
$objQuery=$objConn->query($sql);
$row =$objQuery->fetch();
return $row['TheCount'];
}
$Users = my_count("Users", "Deleted = 0", $objConn);
I am currently using SQL server 2008. I am getting very frustrated because my select statement does not seem to be able to select more than one column. Each time I select from my database table, it displays nothing.
My coding is as follows:
<?php
// build a query to select records from table authorisation to echo out all queries
$query1 = "SELECT * FROM authorisation ";
// execute the query you created above and store the result in a php variable
$result1 = sqlsrv_query($con, $query1) or die(print_r( sqlsrv_errors(), true));
// build a query to select records from table authorisation to echo out all queries
while ($group= sqlsrv_fetch_array($result1) {
$permissiongroup = $group[0];
$permissionpages = $group[1];
echo $permissiongroup;
echo $permissionpages;
}
?>
I used two queries instead and it work. I am not sure why.
// build a query to select records from table authorisation to echo out all queries
$query1 = "SELECT permissiongroup FROM authorisation ORDER BY permissiongroup";
// execute the query you created above and store the result in a php variable
$result1 = sqlsrv_query($con, $query1) or die(print_r( sqlsrv_errors(), true));
// build a query to select records from table authorisation to echo out all queries
$query2 = "SELECT permissionpages FROM authorisation ORDER BY permissiongroup ";
// execute the query you created above and store the result in a php variable
$result2 = sqlsrv_query($con, $query2) or die(print_r( sqlsrv_errors(), true));
while (($group= sqlsrv_fetch_array($result1)) && ($page= sqlsrv_fetch_array($result2)) ) {
$permissiongroup = $group['permissiongroup'];
$pages = $page['permissionpages'];
echo $permissiongroup;
echo $pages;
}
Try this
<?php
// build a query to select records from table authorisation to echo out all queries
$query1 = "SELECT permissiongroup,permissionpages FROM authorisation ORDER BY permissiongroup";
// execute the query you created above and store the result in a php variable
$result1= sqlsrv_query($con, $query1) or die(print_r( sqlsrv_errors(), true));
// build a query to select records from table authorisation to echo out all queries
while ($group= sqlsrv_fetch_array($result1)) {
$permissiongroup=$group['permissiongroup'];
$permissionpages=$group['permissionpages'];
echo $permissiongroup;
echo $permissionpages;
}
?>
Explanation (If this is the solution):
If this resolves your problem, it means permissiongroup and permissionpages are not the first two consecutive columns of the table authorisation. select * from [tablename] will always return the resulset with column names in the same order as present in the table structure. It is advised to use column names instead * to increase performance and many more conflicts like this.
ELSE
In case this doesn't help, please let me know.