I have a MySQL table with stock information including what main industry sector and sub sector a stock belongs to (for example the Coca-Cola stock belongs to the industry sector "Consumer Goods" and to the sub sector "Beverages - Soft Drinks".
$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());
while ($row = mysql_fetch_row($result)) {
$stocks[$i]['name'] = $row[0];
$stocks[$i]['industrysector'] = $row[1];
$stocks[$i]['subsector'] = $row[2];
$i++;
}
$stocksTotals = array();
foreach($stocks as $amount) {
$stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name'];
}
foreach($stocksTotals as $name => $amount) { echo $name.": ".substr($amount,1)."<br>"; }
My problem is that I don't get the code to handle the third level. I want to first output all of the industry sectors (Basic material for example), then all subsectors (Basic Resources for example) for each industry sector, then all names of the stocks corresponding to each subsector.
Currently I only get industry sector and then the stock name, because I fail to understand how to handle this in the array handling code.
Any advise would be highly appreciated! I have put a image here (http://imageshack.us/photo/my-images/853/mysqltophp.gif/) for better reference.
Thanks!
the foreach loop needs to be like this:
//considering you want the value as "$amount['industrysector'], $amount['name']"
foreach($stocks as $amount) {
// $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name'];
echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
}
you dont need another foreach loop.
Edit: you would need to change the way you fetch your rows too,
while ($row = mysql_fetch_assoc($result)) {
$stocks[$i]['name'] = $row['name'];
$stocks[$i]['industrysector'] = $row['industrysector'];
$stocks[$i]['subsector'] = $row['industrysector'];
$i++;
}
foreach($stocks as $amount) {
$output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
if( $amount['name'] !== '' )
$output .= "<br>" . $amount['name'];
";
}
Related
I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}
I have three tables all of them containing data about different partners for the company, there is a Hierarchy already in place, Sales Partners are under Holiday Partners and these, in turn, are under Super Partners, all of this data is already in the database, now I need to show the business carried forward by the sales partner on the holiday partner's dashboard (of the sales partners under him) and same for the superpartners.
The problem is that I am not able to retrieve the data about the next subsequent level of the hierarchy, like, on the dash of holiday partners, I am only able to display the data about the holiday partners and not the sales partners under him.
Already tried removing the foreach loop, as I know it unnecessarily increases complexity, tried keep if-elseif condition to no avail.
case "Holiday Partner":
//2nd level, need holiday as well as sales partners
$case = 2;
//holiday partner data, i.e getting to know which holiday partner we're talking about
$sql2 = "SELECT sno, district, state FROM holidaypartners WHERE name = '$userid'";
$res = $conn->query($sql2);
if ($res->num_rows)
{
if($row = $res->fetch_assoc()){
$sno = $row["sno"];
$district = $row["district"];
$state = $row["state"];
}
}
echo"$sno - "; //this is getting printed
//got sno of holiday partner
$sql1= "SELECT * FROM agent_form_data
WHERE sales_partner_name ='".$sno."' and formstatus = 'pending'";
$res = $conn->query($sql1);
//check for forms filled by the holiday partner himself
if ($res->num_rows){
while($row = $res->fetch_assoc()){
$datesent =date_create($row["datesent"]);
$datesent =date_format($datesent,"d-M-Y");
echo "<tr>
<td>GHRN".(5000+(int)$row["ref_num"])."</td>
<td>".$row["cust_firstname"]." ".$row["cust_lastname"]."</td>
<td>".$row["holi_dest"]."</td>
<td>".$row["date_of_travel"]."</td>
<td>".$row["return_date_of_travel"]."</td>
<td>".$row["duration"]."</td>
<td>".$datesent."</td>
</tr>";
}
}
//sales partner data
$sql = "SELECT sno FROM salespartners WHERE holiday_partner_sno = '$sno'";
$res = $conn->query($sql);
if ($res->num_rows){
while($row = $res->fetch_assoc()){
$nums = array_values($row); //converting into a normal array for the foreach loop
foreach($nums as $val){
echo "$val "; //here only the first value is getting printed, suppose there are four sales partners under him, 6001,6002,6003,6004, now on execution, it prints only 6001, if there is no data to show it simply exits *all* the loops.
$sql2= "SELECT * FROM agent_form_data
WHERE sales_partner_name ='".$val."' and formstatus = 'pending'";//on the other hand, if I remove the SQL part, all the ids under this holiday partner are getting printed, which proves that the array has it but SQL for some reason isn't checking all of the members of the array
$res = $conn->query($sql2);
if($res->num_rows){
echo"Hi!";
while($row = $res->fetch_assoc()){
echo $row["ref_num"];
$datesent =date_create($row["datesent"]);
$datesent =date_format($datesent,"d-M-Y");
echo "<tr>
<td>GHRN".(5000+(int)$row["ref_num"])."</td>
<td>".$row["cust_firstname"]." ".$row["cust_lastname"]."</td>
<td>".$row["holi_dest"]."</td>
<td>".$row["date_of_travel"]."</td>
<td>".$row["return_date_of_travel"]."</td>
<td>".$row["duration"]."</td>
<td>".$datesent."</td>
</tr>";
}
}
else{
echo "No Data";
}
}
}
}
break;
I am not getting any errors as such, as there are no syntactical blemishes, however, I should be able to cycle through all the elements (ids of the partners under a holiday partner) for the required result.
You need to write your code more cleanly. You name all your queries and results similarly resulting to overwrites.
I tried to write your query more cleanly so that you will get the idea. I cannot test since I don't have the db but this should be enough to get you going.
$query_salespartners = "SELECT sno FROM salespartners WHERE holiday_partner_sno = '$sno'";
$res_salespartners = $conn->query($query_salespartners);
if ($res_salespartners->num_rows) {
while($row = $res->fetch_assoc()){
$val = $row['sno'];
echo "$val "; //here only the first value is getting printed, suppose there are four sales partners under him, 6001,6002,6003,6004, now on execution, it prints only 6001, if there is no data to show it simply exits *all* the loops.
$query_sales= "SELECT * FROM agent_form_data
WHERE sales_partner_name ='".$val."' and formstatus = 'pending'";//on the other hand, if I remove the SQL part, all the ids under this holiday partner are getting printed, which proves that the array has it but SQL for some reason isn't checking all of the members of the array
$res_sales = $conn->query($query_sales);
if($res_sales->num_rows){
echo"Hi!";
while($row_sales = $res_sales->fetch_assoc()){
echo $row_sales["ref_num"];
$datesent =date_create($row_sales["datesent"]);
$datesent =date_format($datesent,"d-M-Y");
echo "<tr>
<td>GHRN".(5000+(int)$row_sales["ref_num"])."</td>
<td>".$row_sales["cust_firstname"]." ".$row_sales["cust_lastname"]."</td>
<td>".$row_sales["holi_dest"]."</td>
<td>".$row_sales["date_of_travel"]."</td>
<td>".$row_sales["return_date_of_travel"]."</td>
<td>".$row_sales["duration"]."</td>
<td>".$datesent."</td>
</tr>";
}
}
}
}
Good day # all.
I've this code snippet which's aim is to display the Exam this user is qualified to take based on the courses registered for. It would display the Exam Name, Date Available, Passing Grade and either Take Exam link if he/she hasn't written or View Result if he/she has written previously.
/*Connection String */
global $con;
$user_id = $_SESSION['user_id']; //user id
$courses = parse_course($user_id); //parse course gets the list of registered courses (Course Codes) in an array
foreach ($courses as $list)
{
$written = false;
$list = parse_course_id($list); //parse_course_id gets the id for each course
$ers = mysqli_query($con, "Select * from exams where course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
$trs = mysqli_query($con, "Select * from result_data where user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs)) {
if ($trows['user_id'] == $user_id && $trows['exam_id'] == $erows['exam_id'])
$written = true;
else
$written = false;
}
if($written)
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'View Result '."</td></tr>";
$written = false;
}
else
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'Take Exam '."</td></tr>";
$written = false;
}
}
}
But It only displays one View Result entry even if I've taken more than one exam. It shows the recent entry. Please what am I missing?
Untested, but here's how I would do it.
I've assumed $user_id is an integer. I'm a bit worried about it being used in SQL without any sanitization. I can't guarantee anything else you're doing is secure either because I can't see your other code. Please read: http://php.net/manual/en/security.database.sql-injection.php
(Oh I see someone already commented on that - don't take it lightly!)
Anyway, my approach would be to collect the user's written exam IDs into an array first. Then loop through the available exams and check each exam id to see if it's in the array we made earlier.
I wouldn't bother looking into the join advice unless you find this is performing poorly. In many systems it would be common to have 3 functions in this situation, one that generates $users_written_exam_ids ones that pulls up something like $all_available_exams and then this code which compares the two. But because people are seeing both queries here together there is a strong temptation to optimize it, which is cool but you probably just want it to work :)
<?php
global $con;
// Get the user id. Pass through intval() so no SQL injection is possible.
$user_id = intval($_SESSION['user_id']);
// Parse course gets the list of registered courses (Course Codes) in an array
$courses = parse_course($user_id);
foreach ($courses as $list)
{
// Gets the id for each course
$list = parse_course_id($list);
$users_written_exam_ids = array();
$trs = mysqli_query($con, "SELECT exam_id FROM result_data WHERE user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs))
{
$users_written_exam_ids[] = $trows['exam_id'];
}
$ers = mysqli_query($con, "SELECT * FROM exams WHERE course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
echo '<tr><td>' . $erows['exam_name'] . '</td><td>' . $erows['exam_from']
. ' To ' . $erows['exam_to'] . '</td><td>' . $erows['passing_grade']
. '%</td><td>';
if (in_array($erows['exam_id'], $users_written_exam_ids))
{
echo 'View Result';
}
else
{
echo 'Take Exam';
}
echo '</td></tr>';
}
}
First of all, im a beginner so please excuse me if i don't mention things that could be important.
I have Sellers, that are in different countries in the world. Each country belong to a continent. Im trying to:
get the seller name
Fetch Database to see in what countries (China,Italy,Germany...) he offers his goods.
Then fetch another database and see in what continents (ASIA,EU) belong each country
Store the countries (Italy,Germany) to a variable $country_eu and $country_asia (China). So later i will add this variables to update database fields.
if($continent == 'ASIA') is not included in the code YET since i take one by one the steps. I want to make first EU work, then i figure out the rest.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name;
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
}else{
$flags_string = '';
}
$cont_eu = '';
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if ($continent == 'EU') {
$cont_eu .= $flag_image;
}
}
echo $cont_eu;
The problem with my code is that when i echo $cont_eu is giving me just 1 result(Germany) and not the EXPECTED (Italy,Germany)
Thank you all for your precious time and attempts to help. Here is the new code that works great.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name.'<br>';
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
} else {$flags_string = '';}
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if($continent == 'EU'){ $eu_flags_array[] = $flag_image;}
}
}
print_r($eu_flags_array); //Gives me Array ( [0] => Germany.png [1] => Italy.png )
I need to be able to display the course_desc on line 30, beside the course_name.
<?php
$result = $db->query("select distinct c.dbid, c.course_name, c.course_image, m.module_id, m.module_name, m.module_name_id, m.module_image, m.hasFiles, m.files from courses c join modules_to_courses mc on (c.dbid = mc.courses_id) join modules m on (mc.modules_id = m.module_id)");
$course_name = $db->query("SELECT distinct course_name, course_desc FROM courses");
while ($temp = $course_name->fetch_assoc()) {
$courses[] = $temp['course_name'];
}
$final = array();
// Retrieve results
while ($row = $result->fetch_assoc()) {
// Add to final array via counter if valid course is found
if (in_array($row['course_name'], $courses)) {
$final[$row['course_name']][] = $row;
}
}
// Display if final array is not empty
if (!empty($final)) {
// Loop through each potential course name
foreach ($courses as $name) {
// Output if the course has values within the final array
if (array_key_exists($name, $final)) {
echo '<div>'."\n";
echo ' '. $name . "\n";
echo '<!-- list of modules -->'."\n";
// Loop through internal values
foreach ($final[$name] as $value) {
$module_name = $value['module_name'];
echo ' '. $module_name ."\n";
}
echo ' </div>'."\n";
}
}
}
?>
You already having your course description in $final so you can access it using,
$final[$name]['course_desc']
I have created a paste based on your with changes. Also note that it's need to change your $final array.
distinct course_name, course_desc means you are trying to fetch the values regarding to distinct course_name and distinct course_desc together. You may wanna use group by instead. If I understood correctly, your statement will not bring you distinct course names and their related course desc. (if that is what you want)