I'm having problem on dividing two values and it keeps showing
Warning: Division by zero in ...
I've read and tried some post about dividing values in here but I can't still solve the problem.
This is the snippet :
$query2 = "SELECT SUM(jumlah_poin) AS jumlah_mk FROM tbl_nilai WHERE nama_mk = 'Pengantar Teknologi Informasi'
AND nip_dsn = '198'";
$result2 = mysql_query($query2);
$row2 = mysql_fetch_assoc($result2);
$query4 = "SELECT count(1) FROM tbl_nilai WHERE nama_mk = 'Pengantar Teknologi Informasi'
AND nip_dsn = '198'";
$result4 = mysql_query($query4);
$row4 = mysql_fetch_array($result4);
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 [0];
echo json_encode(array($resultArray,$sum));
and I need to make it in one echo. Any explanation you can provide to a newb will be appreciated. help and teach me please :D
To prevent the devide by zero error I might put it in an if statement
if( $row4[0] != 0 ) { // any falsy value would evaluate to zero
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 [0];
} else {
$sum = $sum_default_value;
}
There are two reasons, try one of this:
Change query to
$query4 = "SELECT count(1) as totalCount FROM tbl_nilai WHERE nama_mk ='Pengantar Teknologi Informasi' AND nip_dsn = '198'";
and
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 ['totalCount'];
Your 2nd query returns count as 0, if no record match.
Related
UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);
I have the following code which displays only 1 result. However, I have six rows in my database with product_id = '1'. I'm talking about $order, only one shows up, instead of six. What is wrong?
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_assoc($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
My database structure:
id (primary & autoincrement)(int 11)
product_id (int 11)
number (int 11)
ordernummer (int 11)
as your id is int, you dont need to use ''
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
try this.....
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1'
LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
echo "$row[ordernummer]";
echo "<br />";
echo "$row[artikelnummer]";
}
There are two things that I notice immediately that shouldn't make a difference, but might be worth trying just to see if it does. First, assuming that the product_id column is a numeric column instead of a string, try using just 1 instead of '1'. Second, explicitly check the result of mysql_fetch_assoc() against FALSE instead of any expression that might evaluate equivalent to false.
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
Edit:
What do you get if you change your code to the following?
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
$index = 0;
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo $index++ . ": <strong>$order</strong><br />";
}
Specifically, does it count all the way from 0 to 7, or does it just show row 0? I'm thinking that it's got to be one of the following:
You really are only getting back one row of results (which is contradicted by your statement that mysql_num_rows() is returning 8),
mysql_fetch_assoc() is incorrectly returning FALSE after just one row (which indicates some kind of bug affecting PHP or the MySQL driver, which is typically very unlikely), or
it is iterating through the loop like it should be, but you are misinterpreting the result, per Marc B's comment regarding empty tags.
This might effectively help narrow down which it is.
I am trying to store a mysql value into a php variable. I have the following query which I know works. However, I the value for $count is always 0. Can someone explain what I need to do to get the count value? The count should be the count of x's w here name_x=.$id.
$query = "SELECT COUNT(name_x) FROM Status where name_x=.$id.";
$result = mysql_query($query);
$count = $result;
Is first letter in table name is really capital. Please check it first.
or Try :
$query = "SELECT COUNT(*) as totalno FROM Status where name_x=".$id;
$result = mysql_query($query);
while($data=mysql_fetch_array($result)){
$count = $data['totalno'];
}
echo $count;
$query = "SELECT COUNT(*) FROM `Status` where `name_x`= $id";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$count = $row[0];
please try it
$query = "SELECT COUNT(*) FROM Status where name_x=$id";
$result = mysql_query($query);
$count = mysql_result($result, 0);
You are missing single quotes around $id. Should be
name_x = '" . $id . "'";
Is there an easier way to do this instead of writing the same line of code 100+ times? I need the value of the field L_key each time as you will notice:
$query1 = "SELECT L_key FROM profiles WHERE v_key = '$L1_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result))
{
$L2_key = $row['L_Key'];
$query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L2_key'";
mysqli_query($dbh, $query2);
}
$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L2_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result))
{
$L3_key = $row['L_Key'];
$query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L3_key'";
mysqli_query($dbh, $query2);
}
$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L3_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result))
{
$L4_key = $row['L_Key'];
$query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L4_key'";
mysqli_query($dbh, $query2);
}
$query3 = "SELECT L_key FROM profiles WHERE v_key = '$L4_key'";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result))
{
$L5_key = $row['L_Key'];
$query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$L5_key'";
mysqli_query($dbh, $query2);
}
Do I use a loop? If so, can you please show me a code to execute this over and over as I am still learning and do not know what a loop is? Or, is there a different method?
You have a recursive structure in your profiles table (v_key => (l_key : v_key)=> ( l_key... )) and SQL does not really handle recusion terribly well with simple queries. Your options are to write a stored procedure or handle this with PHP. Since your a beginner, I'd imagine that PHP is far simpler for this task:
<?php
// define a variable on the outside -- we'll need it for each iteration
$lKey;
// If you know how many are going to be used, use a for loop because
// then you know you won't get some sort of nasty infinite recursion issue.
// $count is however many times this needs to operate.
for($i = 0; $i < $count; $i++ )
// while( true ) // <-- this will keep going until "break" is called.
// If you don't know how many will be used. Comment out the for loop
// and uncomment thie while loop.
{
// your initial query -- I added a limit because you only need one
// and there is no sense in doing anything more than what you need
$query1 = "SELECT L_key FROM profiles WHERE v_key = '$lKey' LIMIT 1";
$result = mysqli_query($dbh, $query1);
if ($row = mysqli_fetch_array($result)) // so far so good.
{
$lKey = $row['L_Key']; // assign that outside variable to the new key
// and run the necessary update.
$query2 = "UPDATE profiles SET min = min + 1 WHERE v_key = '$lKey'";
mysqli_query($dbh, $query2);
}
else
{
break;
}
// as of right now, $lKey is now the value from the select above.
// which means that you'll be able to start the next loop with it.
}
If I understand correctly, you can use the mysql_num_rows OR mysql_result to get the total numbers, so you can use a while:
<? $a = 0; while($total != $a) { //query $a++; } ?>
Use pdo and solve all your worries. This is cinche in pdo using prepared statements. Will even perform better.
$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'