With the first query in the following code I am looking for the checkings made in Berlin under the game number two.
With the second query I want to give points for each of the checkings.
As you will see I am using the function SUM. But let's say that I have 2 checkings and the points for each checking are 50. Well, instead of echoing 100, with this code I echo 5050
What is wrong with it?
Thanks a lot
THE CODE IS CORRECTED AND WORKING, JUST IN CASE SOMEBODY NEEDS IT. Thanks to all
$querya = "SELECT * FROM checkins where gamesid=2 and city='Berlin'";
$resulta = mysql_query($querya) or die(mysql_error());
$sumOfPoints = 0;
while($rowa = mysql_fetch_array($resulta)){
$n = $rowa['venuesid'];
$queryb = "SELECT venuesid, SUM(points) as sumpoints from venues where venuesid='".$n."' GROUP BY venuesid ORDER BY venuesid";
$resultb = mysql_query($queryb) or die(mysql_error());
while($rowb = mysql_fetch_array($resultb)){
$sumOfPoints += $rowb['sumpoints'];
}
}
echo "Total points is $sumOfPoints<br/>";
Some suggestions
Use SUM(points) AS sum (only for clarity when use the sum)
Check that points are numerical fields not varchar.
points must be a string, you need to cast it
SUM(cast(points) as int)
and then follow Gaurav's point about labeling the compute
You're getting 5050 because your script is echoing 50 in two iterations of the loop.
From the looks of it, your second query's GROUP BY clause is not grouping on venuesid when it should be. So, first try changing your GROUP BY clause to:
GROUP BY venuesid
If that doesn't give you the result you're looking for, then you should try running your query directly against the database with a static value for venuesid to see what you get back from it, then perhaps update your question and we can take it from there.
Related
Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.
I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is
2, 000002 (which is correct) that is what I am looking for.
$itemId = $_POST['itemId'];
if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
while($data = $sqlItemId->fetch_assoc()){
printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
die();
}
Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.
I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.
$sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");
if($itemId == $sqlItemId){
echo "This item id is already in use. \n";
die();
} else {
echo "Item Id is not in use:";
die();
}
At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?
Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):
$rowsCount = $dbCon->query("
SELECT COUNT(*)
FROM CVCinStoreCoins
WHERE itemId = '$itemId'
");
I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.
Wy don't you just count it,
$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");
if $result > 0
I just want to Count data from table row. This is code. It works, somehow..
// Query
$result = mysqli_query($con, "SELECT COUNT(answer) as ans FROM answers WHERE questionId = '$id' ");
while($row=mysqli_fetch_array($result))
{
echo $row['ans'];
}
With this code, it count me thing that i want But, behing counting number there is number '1' that shows up. So ih i have 5 answers for specific question, it shows me '51'. Why?
this code will never echo 1.
look your code where are you echoing something that comes with 1.
you are echoing something that comes with 1 exactly after this code
Anyone who could help me it will be greatly appreciated.
Goal: I want to display the id from one table randomly as well as to make sure it has not been seen by the current user.
Two tables: offers, has_seen
I want to pick a random id from offers, check it against the has_seen table.
If the ID exists in the has_seen, it need to re pick another random id. The same ID should never be seen by any one user of the current session.
I cannot seem to figure out how to pick a random one, check the other table, and loop back if found.
I have tried this
$query = $this->db->query("SELECT * FROM ".$this->offer_table." WHERE NOT EXISTS (SELECT * FROM ".$this->shown_table." WHERE ".$this->shown_table.".camp_id = ".$this->offer_table.".camp_id AND ".$this->shown_table.".usercode = ".$this->session->userdata("table")." LIMIT 1 ");
I think that this can be achieved in plain SQL by doing a left join and then checking for null.
Something along the lines of
SELECT * FROM table1 LEFT JOIN table2 USING (shared_key) WHERE table2.id IS NULL ORDER BY rand() LIMIT 1
Here's how you could do it using CI's db class:
// the maximum ID that is acceptable
$max = $this->db->get('first_table')->count();
while(true) {
// get a random number
$randomID = rand(0,$max);
// the condition for which we will check the has_seen table
$condition = array(
'id' => $randomID
);
// if count is 0, it has not been seen. We add it to the table and return
// if it has been seen, the loop will repeat
if ($this->db->get_where('has_seen', $condition)->count() === 0) {
$this->db->insert('has_seen', array(
'id' => $randomID
));
return $randomID;
}
}
SELECT * FROM `offers` WHERE `camp_id` NOT IN (SELECT `camp_id` FROM `has_seen` WHERE `user code` = 1) ORDER BY RAND() LIMIT 1
I always prefer reading the contents of a table into an array and working with them from there. Depending on how you plan to use the results, you could cut down on db accesses by reading it all only once and then serving from the array (and then, I presume, updating the has_seen table for next session).
I must apologize for the pseudocode as it's been years since I've written any PHP.
Once you've got your array, the algorithm looks like this:
var array
var end = array.length
function getNextRandomUnseen
{
var i = rand(end)
var temp = array[i]
array[i] = array[end--]
return temp
}
If you want, you can even stick the seen values at the end of the array so they aren't lost.
array[end+1] = temp
Thanks for the answers. I redid the way it is going to be brought to the user and believe the new way is much more efficient when it comes to hundreds of people on my site at once.
Thanks!
I am trying to grab the total amount of sales made for a a single month
$aug11 = mysql_query("SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011' ");
when I echo $aug11 I get a resource id# error. I also tried to do this
$test1 = mysql_fetch_array($aug11);
and when I echo $test1 it just says "Array".
Is it absolutely necessary to place a GROUP by sales_date in the original query and then have a while loop that grabs the array and lets me echo the values?
I don't really need any other value except the sum of 'price' for the month of August.
Can someone please explain to me how I can display the value I need without a while loop?
use this to get the sum value
$test1[0];
echo $test1[0]; // returns the sum
$aug11 is not a query string, it is the result of a query. When you fetch an array from the result, it is an array of values, not a scalar. I think you want to do this:
$query = "SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011'";
$aug11 = mysql_query($query);
$row = mysql_fetch_array($aug11);
$test1 = $aug11[0];
If I need to know the total number of rows in a table of database I do something like this:
$query = "SELECT * FROM tablename WHERE link='1';";
$result = mysql_query($query);
$count = mysql_num_rows($result);
Updated: I made a mistake, above is my actual way. I apologize to all
So you see the total number of data is recovered scanning through the entire database.
Is there a better way?
$query = "SELECT COUNT(*) FROM tablename WHERE link = '1'";
$result = mysql_query($query);
$count = mysql_result($result, 0);
This means you aren't transferring all your data between the database and PHP, which is obviously a huge waste of time and resources.
For what it's worth, your code wouldn't actually count the number of rows - it'd give you 2x the number of columns, as you're counting the number of items in an array representing a single row (and mysql_fetch_array gives you two entries in the array per column - one numerical and one for the column name)
SELECT COUNT(*) FROM tablename WHERE link='1';
You could just do :
SELECT count(*) FROM tablename;
for your query. The result will be a single column containing the number of rows.
If I need to know the total number of rows in a table of database
Maybe I'm missing something here but if you just want to get the total number of rows in a table you don't need a WHERE condition. Just do this:
SELECT COUNT(*) FROM tablename
With the WHERE condition you will only be counting the number of rows that meet this condition.
use below code
$qry=SHOW TABLES FROM 'database_name';
$res=mysql_query($qry);
$output=array();
$i=0;
while($row=mysql_fetch_array($res,MYSQL_NUM)){
++$i;
$sql=SELECT COUNT(*) FROM $row[0];
$output[$i]=mysql_query($sql);
}
$totalRows=array_sum($ouptput);
echo $totalRows;
http://php.net/manual/en/function.mysql-num-rows.php You need this i think.
If you are going to use the following SQL statement:
SELECT COUNT(*) FROM tablename WHERE link='1';
Make sure you have an index on the 'link' column