PHP File if Condition get different result and error - php

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 "

Related

PHP array_sum outputs individual numbers rather than as a whole

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;

php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.
I want to get the records based on these two id number. But this below code returns the output repeatedly.
How do I properly put the while loop code inside a foreach?
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',' ',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array.
$res = mysql_query($sql)
should be on it's own line before the while loop, and then
while($r = msql_fetch_array($res))
This will properly increment through the $res list.
Try this and you are done
As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',',',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}

some problems with in_array function

Hi I am trying to use in_array, I think my syntax is correct,
but it says "Wrong datatype for second argument"
My code is
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $filter))
{
}
}
My idea is to find out if the ProductID from Products Table is in the Order Table.
Could someone helps me, Thanks :-)
$filter isn't an array; it's a mysqli_result object:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
I think you want to iterate over that, add each ProductID to a new array, and then pass that array to the in_array function like so:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
$product_ids = array();
while ($row = $filter->fetch_assoc())
{
$product_ids[] = $row['ProductID'];
}
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $product_ids))
{
}
}
Your code is failing because $filter is a MySQLi result resource, not an array. Really, this is better accomplished with a simple inner join between the two tables. If a ProductID does not exist in Orders, the INNER JOIN will exclude it from the result set in the first place.
$sql = "
SELECT Products.*
FROM
Products
INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
If instead you want to retrieve all the Products, and simply have an indication of whether it has an active order, use a LEFT JOIN and test if Orders.ProductID is null in the SELECT list:
$sql = "
SELECT
Products.* ,
/* No orders will print 'no-orders' in a pseudo column called has_orders */
CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...
In this case, you may test in a loop over your rowset whether it has orders:
foreach ($results as $r) {
if ($r['has_orders'] == 'has-orders') {
// this has orders
}
else {
// it doesn't...
}
}

SQL / PHP How to pull data from a table and place it in variable

Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories