I have this list of "coupons" each with a unique "productid"
Now I am trying to convert the list into an array using:
$claimed = array($rowOrder['productid']);
My issue is when I try to use "count" and "array_sum" it outputs individual numbers:
$count_claimed = array(count($claimed));
echo array_sum($count_claimed);
Using the echo I get and output of: "1111111"
What should I change to get a sum count of 7? (as displayed with the number of "coupons")
additional info:
The "coupons" are being outputted by this SELECT statement, $rowOrder is calling this.
public function SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid) {
$stmt = $db->prepare(
" SELECT o.orderid, o.productid, o.usrcustomerid, o.amount, o.amountrefunded, o.createddate, o.scheduleddate, o.useddate, o.expirationdate, p.photosrc
FROM `order` o LEFT JOIN `product` p ON o.productid = p.productid
WHERE usrcustomerid = :usrcustomerid"
);
$stmt->bindValue(':usrcustomerid', $usrcustomerid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
This is called like this
$lstInfo = $mcOrder->SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid);
foreach($lstInfo as $rowOrder) {
if (isset($rowOrder['productid']) && ($rowOrder['expirationdate'] > date("Y-m-d H:i:s"))) {
$claimed = array($rowOrder['productid']);
$count_claimed = array(count($claimed));
echo array_sum($count_claimed);
}
}
Doing count($lstInfo) you will get the total number of fetched rows (PDOStatement::fetchAll() returns an array, and you just count the number of elements in it). Then you can loop the results and increment a variable called $claimed if the condition is true.
$lstInfo = $mcOrder->SelectLst_ByUsrCustomerIDInfo($db, $usrcustomerid);
$total = count($lstInfo);
$claimed = 0;
foreach($lstInfo as $rowOrder) {
if (isset($rowOrder['productid']) && ($rowOrder['expirationdate'] > date("Y-m-d H:i:s"))) {
$claimed += 1;
}
}
echo "Claimed $claimed of $total.";
Even better, you can do it in one query using a COUNT() and an added WHERE condition. This means you won't get the total, but that didn't seem to be the question to begin with either.
$stmt = $db->prepare("SELECT COUNT(productid) as cnt
FROM `order` o
LEFT JOIN `product` p
ON o.productid = p.productid
WHERE usrcustomerid = :usrcustomerid
AND expirationdate > NOW()
GROUP BY usrcustomerid");
$stmt->execute([":usrcustomerid" => $usrcustomerid]);
$result = $stmt->fetch();
echo "Claimed ".$result['cnt'];
Try This,
$claimed = array();
foreach($products as $rowOrder){
array_push($claimed,$rowOrder['productid']);
}
echo count($claimed);
echo array_sum($claimed);die;
Related
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
This is Error:
enter image description here
just put below percentage calculation section in brackets and try
(sum(a.Marks)/sum(a.TotalMarks) * 100) as Percentage
In your sql query there is no field with name "Percentage" so that is why you are getting this error
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks, Percentage missing "
I am trying to do a while loop with a prepared PDO statement, but I only want it to execute if there are any rows. Currently I am using this, but it seems to be missing the first result, presumably because its moving the pointer.
What is the right way to do this?
$stmt = $pdo->prepare('SELECT * FROM products p
INNER JOIN products_to_categories c
ON p.products_id = c.products_id
WHERE c.categories_id = ?
AND products_status=?
ORDER BY p.products_sort_order,p.products_name');
$stmt->execute([$categories_id,1]);
if(($category_row = $stmt->fetch(PDO::FETCH_ASSOC)) != null) {
$no_results = count($stmt->fetch(PDO::FETCH_ASSOC));
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// show row info
}
}
What about something like:
$stmt = $pdo->prepare('SELECT * FROM products p INNER JOIN products_to_categories c ON p.products_id = c.products_id
WHERE c.categories_id = ? AND products_status=? ORDER BY p.products_sort_order,p.products_name');
$stmt->execute([$categories_id,1]);
$products_row="some_random_string";
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC) && $product_row!="some_random_string" && $product_row!=false) {
// show row info
}
Since you talked about row count,
$result = $con->prepare("SELECT count(*) FROM `products`");
$result->execute();
$number_of_rows = $result->fetchColumn();
You do not need to check the row count. Simply rewrite:
$stmt = $pdo->prepare('...');
$stmt->execute([$categories_id, 1]);
$rows = 0;
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC) {
// You can increment $rows only if some other condition is met if you want
$rows++;
// show row info
}
switch ($rows) {
case 0:
// No rows were retrieved.
// run the 'different function' you mentioned in the comments
break;
case 24:
print "There are two dozen rows in your results";
break;
}
As requested, the while loop will never execute if there are no results. And if there are, it will loop every one of them.
I have the following query
SELECT fixtures.Fixture_ID, fixtures.Home_Score,
fixtures.Away_Score, predict.Fixture_ID, predict.pHome_Score, predict.pAway_Score
FROM fixtures INNER JOIN predict
ON fixtures.Fixture_ID=predict.Fixture_ID
I want to count the number of times the following condition is met
fixtures.Home_Score=predict.pHome_Score
AND fixtures.Away_Score=predict.pAway_Score
AND fixtures.Fixture_ID=predict.Fixture_ID
I tried using a 'COUNT()' then 'Having count()>1' but cant get the syntax to work
I have also tried to count the number of times the if condition is met in the following php. I'm not sure if this is possible, so I thought the count might have to done within as SQL statement
<?php
$current = $user->data()->id;
$sql2 = "SELECT fixtures.Home_team, fixtures.Away_Team, fixtures.Home_Score, fixtures.Away_Score, predict.pHome_Score, predict.pAway_Score FROM fixtures
INNER JOIN predict
ON fixtures.Fixture_ID=predict.Fixture_ID WHERE predict.id='".$current."'";
echo "The number of detected predictions:", '<br>';
$predictions = DB::getInstance()->query($sql2);
foreach ($predictions->results() as $rows) {
$rows= get_object_vars($rows);
$num_rows= $predictions->count();
}
for($count=0;$count<$num_rows;$count++){
$r_home_score = $predictions->results()[$count]->Home_Score;
$p_home_score = $predictions->results()[$count]->pHome_Score;
$r_away_score = $predictions->results()[$count]->Away_Score;
$p_away_score = $predictions->results()[$count]->pAway_Score;
$p=0;
if($r_home_score==$p_home_score&&$r_away_score==$p_away_score){
$p++;
echo $p;
}
}
The output is:
The number of detected predictions:
111111
I want to output 6
If you just want a single count returned from the database, you could just do a query like this:
SELECT COUNT(*) AS mycount
FROM fixtures f
JOIN predict p
ON p.Fixture_ID = f.Fixture_ID
AND p.pHome_Score = f.Home_Score
AND p.pAway_Score = f.Away_Score
FOLLOWUP
$dbh = DB::getInstance();
$sql = "SELECT COUNT(*) AS mycount
FROM fixtures f
JOIN predict p
ON p.Fixture_ID = f.Fixture_ID
AND p.pHome_Score = f.Home_Score
AND p.pAway_Score = f.Away_Score
WHERE p.id = ?";
if ($sth = $dbh->prepare($sql)) {
$sth->bindParam(1, $current, PDO::PARAM_INT);
if ($sth->execute()) {
if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['mycount'];
} else {
// this should never happen with a COUNT(*) query
echo "query returned 0 rows";
}
} else {
echo "PDO error on execute: ";
print_r($dbh->errorInfo());
} else {
echo "PDO error on prepare: ";
print_r($dbh->errorInfo());
}
I have looked online for a solution to my problem for many hours to no avail.
I have multiple selct statements, receiving data from different mysql tables.
I want to echo completely separated results. Currently, results are printed as if they are one,
so I cannot work on the answers separately.
Suppose the output from table is:
100
200
300
400
I want to echo out:
result1 = 100;
result2 = 200;
etc
So I can work on the final results in another program. If a result is null, it should not produce an error,
but just post 0.
Example, if output from mysql table is:
100
null
null
100
I want the output to clearly show
result1 = 100;
result2 = 0;
result3 = 0;
result4 = 100;
etc.
$check_sco = 100;
$sql = "SELECT TABLE_1 FROM RIDER_1 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_2 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_3 WHERE score1=$check_sco;";
$sql .= "SELECT TABLE_1 FROM RIDER_4 WHERE score1=$check_sco";
if (mysqli_multi_query($con,$sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);//how to echo separated result that can be manipulated indepedently?
}
mysqli_free_result($result);
}
} while (mysqli_next_result($con));
}
Thank you.
Why not just run them in sequence?
$check_sco = 100;
$riders = array();
for($i=1; $i<=4; $i++) {
$sql = "SELECT TABLE_1 FROM RIDER_" . $i . " WHERE score1=" . $check_sco;
$result = mysqli_query($con, $sql);
$row = $result->fetch_assoc();
$riders[] = ($row['TABLE_1']) ? $row['TABLE_1'] : 0;
}
Then you'll have an array with the results you want
You need to use IFNULL which if TABLE_1 is not null it will return TABLE_1 otherwise it will give you 0
SELECT IFNULL(TABLE_1, 0) FROM RIDER_1 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_2 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_3 WHERE score1=$check_sco;
SELECT IFNULL(TABLE_1, 0) FROM RIDER_4 WHERE score1=$check_sco
I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.