This is the query I have:
$sqlw = "SELECT * FROM coverages where user_id='3828' ORDER BY sp_id ASC";
$resultw = mysql_query($sqlw);
$roww = mysql_fetch_array($resultw);
while ($roww = mysql_fetch_array($resultw)) {
echo $roww['sp_id']."<br>";
}
echo "TOTAL:".mysql_num_rows($resultw)."<br>";
As you can see its very basic
the results show : TOTAL:29
But when I count the list of the items returned back its only 28.
I ran the query on phpmyadmin it shows a total of 29 rows, I did count them and they are 29.
I ran different other simple queries and it always does the same thing: one row is missing. This could be trivial maybe I am missing something or maybe its server related? any help/ideas would be greatly appreciated. Thank you
Your call to mysql_fetch_array() before the loop disposes of a row.
You have a classic off-by-one error.
There is an extra $roww = mysql_fetch_array($resultw); before your loop starts. This means you're throwing away the first row.
Related
I'm new to PHP and i want to know how i can subtract a specific amount from the results from counting the total amount of rows in a table. In this case i'd like to minus the value 3 from whatever the value of the total rows is. But i keep getting an error. Below is my code.
$cartwork = $con->query("SELECT count(*) FROM table");
$vs = '3';
$camount = $cartwork - $vs;
echo "$camount";
When the code runs i get the error "Object of class mysqli_result could not be converted to int" what can i do to fix this and get it to work properly.
The query returns a result set. You need to parse through the result set(s) in order to access the values returned. That's basically what the error states.
Please see here for documentation on the PHP function for fetching rows:
http://php.net/manual/en/function.mysql-fetch-row.php
So basically you would need
$row=$cartwork->mysql_fetch_row();
$cartWork_value = $row[0];
$vs = '3';
$camount = $cartwork_Value - $vs;
echo "$camount";
Note - this assumes that you get back exactly one result row (which should be the case with your query).
You can simply change your query to:
$cartwork = $con->query("SELECT count(*)-3 FROM table");
It doesn't smell particularly good though.
I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.
Hello stackoverflow, long time lurker first time asker. Anyways I am creating a project for my school and it is almost completely finished but I think I need help with the while loop. I am trying to sum the variables that are stored in the array and then output that into a useable variable that I can sum with another variable. The problem is the loop only does 1 iteration every time I refresh to page. So it will eventually get the full array but only one item at a time. Please let me know what I am going wrong, I'm sure its something dumb!
$bill= mysql_query("SELECT Transaction.date, Transaction.Price, Transaction.customer_customer_id, Service.cost, Service.user_id, Service.uname
FROM *.Transaction,*.Service
WHERE Transaction.customer_customer_id = Service.user_id AND Service.uname = '$uuname'");
$query_row=mysql_fetch_array($bill);
$userservice = ($query_row[cost]);
$userprice = ($query_row[Price]);
$row2=array();
while($row = mysql_fetch_array($bill))
{
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Thanks for any help you guys may have. This one is frying my brain.
Both your SQL and your PHP make no sense.
FROM *.Transaction,*.Service
...will throw an error in MySQL, but your code doesn't check for errors. I suspect it should be:
FROM Transaction, Service
While the PHP will parse and run.....
while($row = mysql_fetch_array($bill)) {
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Is a very strange way to populate an array. Why not just....
while($row = mysql_fetch_array($bill)) {
$totalservice+=$row['cost'];
}
Indeed, if you are just throwing away the rest of the data, then why are you fetching it from the database?
SELECT SUM(Service.cost)
FROM Transaction,Service
WHERE Transaction.customer_customer_id = Service.user_id
AND Service.uname = '$uuname'
In which case the join is also redundant:
SELECT SUM(Service.cost)
FROM Service
WHERE Service.uname = '$uuname'
Rewrite query as
SELECT Service.user_id, Service.uname, SUM(Service.cost) as cost
FROM djqrico_hotel.Transaction LEFT JOIN djqrico_hotel.Service ON Transaction.customer_customer_id = Service.user_id
WHERE Service.uname = '$uuname' GROUP BY Service.user_id
if you want to get sum of all user's transactions.
The problem is the loop only does 1 iteration every time I refresh to page.
Have you ran the query against the database and checked if it's returning more than one row?
Also, if all you want to do is sum the cost column you could do that in sql:
SELECT SUM(cost)[....]
I have a mysql query:
$a=mysql_query("SELECT id FROM table1 WHERE p2='fruit' LIMIT 1");
This will only ever return one result or none.
I'm trying to first count the results, then if it 1, to pass the returned id to a variable.
Question: If I do
$results=count(mysql_fetch_assoc($a));
to count the number of rows returned, can I still do later
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
or will the first delete the array somehow???
Is their a better way to do all this?
You really not need to do anything if there is one row or null
Consider below code it will set id value if there is 1 row fetched otherwise it will be null
$id=''
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
No count needed.
$results=count(mysql_fetch_assoc($a));
does not count the number of rows as mysql_fetch_assoc returns one row. I believe you're looking for mysql_num_rows:
$results = mysql_num_rows($a);
$num_rows = mysql_num_rows($a);
You can then do an IF statement on this and later do a while loop on the fetched array
Have you tried mysql_num_rows ??
http://php.net/manual/en/function.mysql-num-rows.php
What happens when using:
while($row = mysql_fetch_array($a)){
$id=$row['id'];
}
it is just like reading a file,every time mysql_fetch_array($a) is called the next line is parsed untill it reaches the end of the file. A cursor of some sort is known in the background. Meaning that if you would enter by hand
//backgroundCursor = 0
$row = mysql_fetch_array($a)
//backgroundCursor = 1
$row = mysql_fetch_array($a)
//backgroundCursor =2
$row = mysql_fetch_array($a)
//backgroundCursor = 3
The while instruction just automates the stuff.
mysql_fetch_array increases the background cursor at every call so if you call it twice it will not give you the same line.
To get a clear view on this read something about reading from a file line by line.
No you cannot as each call to mysql_fetch_assoc() loads a new row, if there is any. You could indeed assign both variables at once:
$results=count($row = mysql_fetch_assoc($a));
but
But mysql_fetch_assoc($a)) returns false and as the result of count(false) is 1 this will not tell you anything. Besides, if there is no row all you really need is $row = mysql_fetch_assoc($a) and test if ($row) {...}.
I use this code to output all threads with a specific forum ID
$query = mysql_query("SELECT * FROM forums JOIN threads ON threads.fid = forums.id WHERE forums.id = ".intval($_GET['forumID']));
$forum = mysql_fetch_assoc($query);
?>
<h1><a>Forums</a> > <?=$forum['name']?></h1>
<?php while ($thread = mysql_fetch_array($query)): ?>
<?=$thread['title']?>
<?php endwhile; ?>
forums
id, name, description
threads
id, title, message, fid
Thing is that it outputs all threads exept one. If I remove one it just hides another. Why is that?
Would really appreciate some help!
sorry my english is not that good, lets say i have 4 records in threads with fid = (in this case 1), it only outputs 3 of them
You are using the first row returned in the mysql_fetch_assoc in line 2. In your while loop condition, the mysql_fetch_array function will starts with the second row of the sql query, not the first. Therefore, the id from the first row is missing in your list. However, if you use the column name, you should also use mysql_fetch_assoc, not mysql_fetch_array. This should not give you any ids.
The reason you have one fewer threads than you're expecting is that you're fetching the first thread in line 2, but only using it to display the forum name. You then fetch the second row in the while loop and start from there to list the threads - missing the first row.
I'd refactor your code using the do..while control structure in PHP, as follows:
$query = mysql_query("SELECT * FROM forums JOIN threads ON threads.fid = forums.id WHERE forums.id = ".intval($_GET['forumID']));
$thread = mysql_fetch_assoc($query);
if ($thread != null) {
echo "<h1><a>Forums</a> > $thread['name'] </h1>";
do {
echo $thread['title'];
} while ( $thread = mysql_fetch_array($query)) );
}
As txwikinger pointed out, the internal array pointer is moved forward by mysql_fetch_assoc(), so the first time you use mysql_fetch_array(), you'll get the second row. You can reset the array pointer with mysql_data_seek() before using the array a second time.
mysql_data_seek($query, 0);
I'd rather restructure the code to use two queries though, one to get the forum name in one tiny query, and one to get all the threads in another query.