trying to show a total from mysql in php - php

I am trying to get the qunt with are int and add them all up and show a total
$qunt = 0;
$result = mysql_query("SELECT *
FROM properties_items
WHERE user_propid='$view'
ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$itemid = $row['itemid'];
$qunt = $row['qunt'];
$qunt++;
}
echo $qunt;

$qunt = 0;
$result = mysql_query("SELECT *
FROM properties_items
WHERE user_propid='$view'
ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$itemid = $row['itemid'];
$qunt += $row['qunt'];
}
echo $qunt;
Dare I say that you probably aren't using the itemid, in which case there's no point in looping through a result set in code. Instead, try something like this:
$qunt = mysql_query "SELECT SUM(qunt) FROM properties_items WHERE user_propid='$view'";

$qunt += $row['qunt'];
And get rid of the ++ line.

Related

Subtracting array values

I am getting data from a MySQL database using an array (via PHP).
I was wondering, is it okay to subtract array values, like this (on line 7):
$num = 30;
$result1 = mysql_query('SELECT * FROM table1');
$result2 = mysql_query('SELECT * FROM table2');
while($row1 = mysql_fetch_array($result1) && $row2 = mysql_fetch_array($result2)) {
$sub = $row1['number'] - $row2['number'];
if($sub<=$num) {
echo $row1['person'];
}
I'm actually not getting any results back (just blank). So I was wondering if that line or any parts of my code is logically correct?
Try like this
$num = 30;
$result = mysql_query('SELECT number.table1 as n1, number.table2 as n2, colName.tableName FROM table1 JOIN table2 ON id.table1 = table1_id.table2');
while($row = mysql_fetch_array($result)) {
$sub = $row['n1'] - $row['n2'];
if($sub<=$num) {
echo $row['person'];
}
}

PHP MySQL How can I paginate within two while loop

I would like to know how can I do a LIMIT 0,10 in this case (in order to do a pagination later) because when I do this I obtain a total of 30 results (10 results for each result of the first loop) which is logical, any idea ?
$select = "SELECT X FROM Y"
$result = mysql_query($select,$link);
$total = mysql_num_rows($result);
while($row = mysql_fetch_array($result)) {
$Name = $row['X'];
$select2 = "SELECT id FROM `".$Name."` LIMIT 0,30 ";
$result2 = mysql_query($select2,$link) or die ('Erreur : '.mysql_error() );
$total2 = mysql_num_rows($result2);
while($row2 = mysql_fetch_array($result2)) {
echo $row2['id']
}
}
Thanks in advance for your help !

How can I improve this PHP MySQL call?

I'm trying to update an older MySQL PHP method call but I end up calling the same SELECT call twice to achieve the same result. Is there a better way to do this?
Here is the original:
function updateProbabilities()
{
// first update the word count of each category
$rs = $this->con->select("SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id");
$total_words = 0;
while (!$rs->EOF()) {
$total_words += $rs->f('total');
$rs->moveNext();
}
$rs->moveStart();
if ($total_words == 0) {
$this->con->execute("UPDATE nb_categories SET word_count=0, probability=0 WHERE 1");
return true;
}
while (!$rs->EOF()) {
$proba = $rs->f('total')/$total_words;
$this->con->execute("UPDATE nb_categories SET word_count=".(int)$rs->f('total').",
probability=".$proba."
WHERE category_id = '".$rs->f('category_id')."'");
$rs->moveNext();
}
return true;
}
Here is my version:
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row['total'];
}
if ($total_words >= 1) {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$proba = $row['total']/$total_words;
$count = (int)$row['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}
Do you see any way I can avoid this second duplicate SELECT call?
The first time you run the query, add this to the while loop to store the results:
$rowarray[] = $row; // added to prevent running it twice
Then the second time it comes up, replace this:
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
with this:
foreach ($rowarray as $row) {
ALSO: move away from mysql_ functions, as they are deprecated and will soon be removed from PHP. Change to a PDO or MySQLi. You're already upating the code, may as well make that change too.
The mysql equivalent of $rs->moveStart() is:
mysql_data_seek($res, 0);
P.S. If you're rewriting into a new API, why are you using the deprecated mysql extension? You should use mysqli or PDO? They have similar methods for rewinding the cursor.
You can set the first query to a unique variable, and re-use the results of that query.
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
$results = array();
while ($row1 = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row1['total'];
$results[] = $row1;
}
if ($total_words >= 1) {
foreach ($results as $row2) {
$proba = $row2['total']/$total_words;
$count = (int)$row2['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row2['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}

problem with calculating all elements in array

$query = $db->query("SELECT * FROM orders");
while ($row = mysql_fetch_array($query)) {
$cost= array_sum($row['cost']);
}
This is not working, I want to to calculate the sum of all elements but I get this error:
Warning: array_sum() expects parameter
1 to be array, string given in
C:\xampp\htdocs\falco\classes\controller.php
on line 303
Any idea how to calculate all the elements coming from mysql?
Thank you for your time and help.
Why not let MYSQL handle it?
$query = $db->query("SELECT orders.*,SUM(cost) as sum_cost FROM orders");
If its just a sum you want you can let the database do it for you:
Select sum(cost) from orders
Try this:
$query = $db->query("SELECT * FROM orders");
$cost = 0;
while ($row = mysql_fetch_array($query)) {
$cost += $row['cost'];
}
Or from mysql:
$query = $db->query("SELECT sum(`cost`) as `cost` FROM orders");
while ($row = mysql_fetch_array($query)) {
$cost = $row['cost'];
}
this should work:
$query = $db->query("SELECT * FROM orders");
$cost = 0;
while ($row = mysql_fetch_array($query)) {
$cost += $row['cost'];
}
or even better
$query = $db->query("SELECT SUM(cost) FROM orders");
list($cost) = mysql_fetch_row($query);
Really, it sounds like you just want the sum.
'SELECT SUM(cost) as sum_cost FROM ORDERS'

$row=mysql_fetch_array($result); only returns even rows

We have this code:
$rowArray;
$rowID = 1;
$query = "SELECT idCentros FROM centros";
$result = mysql_query($query);
$numrows=mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$rowArray[$rowID] = $row['idCentros'];
$rowID = $rowID +1;
}
$numrows returns 4 (the rows we have in that table)...but for an unkown reason the loop starts retrieving the 2º row next it retrieves the 4º row and then it ends the loop ($row =false). As we understand this is generic code and the table definition is like this:
column idcentros int(11) pk notnull autoincremental
column nombre mediumtext
What could be happening? Thanks in advance...
try this:
$query = "SELECT idCentros FROM centros";
$result = mysql_query($query);
$numrows=mysql_num_rows($result);
$rowArray = array();
while($row = mysql_fetch_array($result))
{
array_push($rowArray,$row);
}
I don't see why the above code shouldn't work, but ... here's how I would do it:
$rowArray = array();
$query = "SELECT idCentros FROM centros";
$result = mysql_query($query);
$numrows=mysql_num_rows($result);
while($row = mysql_fetch_row($result)){
$rowArray[] = $row[0];
}
... I believe you have $rowID set to 1 just for visualisation later, but it's pointless - you should use HTML lists or some $counter++ variable for the output.

Categories