PHP - Working Out A Grand Total From Multiple Mysql Tables
Basically I want to add up multiple tables and display a grand total on my page when the radio button is pressed. The radio button has values that connect to my database and the values link to and ID with a price. How can I use this code in order to work out a grand total? Many thanks. I have searched everywhere but found nothing.
Similar TutorialsHello I am very new to php and programming and I need a grand total of "$Total = odbc_result($result, "total");" but not sure of how to create it. Hi guys, I'm trying to query two tables for different data and echo the results that match both tables. Here are the tables I have and the query I'm trying to run. (Table) qc_reports (Fields) id report_date report_lot_number report_po report_supplier report_buyer report_inspectedby report_pulptemprange report_carrierconditions report_supplierclaim report_carrierclaim report_temprecorder report_temprange_N report_temprange_M report_temprange_B report_suppliercontact report_contactedby report_time report_comments (Table) qc_lots (Fields) id report_id lot_temprange lot_commodity lot_rpcs lot_brand lot_terms lot_cases lot_orgn lot_estnum lot_avgnum This is the query that I'm trying to do. Code: [Select] <?php $sql = "SELECT * FROM qc_reports, qc_lots WHERE "; if (!empty($start_date) and !empty($end_date)) $sql .= " qc_reports.report_date BETWEEN '$start_date' and '$end_date' AND "; if (!empty($search_fronteralot)) $sql .= " qc_reports.report_lot_number = '$search_fronteralot' AND "; if (!empty($search_buyer)) $sql .= " qc_reports.report_buyer = '$search_buyer' AND "; if (!empty($search_supplier)) $sql .= " qc_reports.report_supplier = '$search_supplier' AND "; if (!empty($search_po)) $sql .= " qc_reports.report_po = '$search_po' AND "; if (!empty($search_carrierconditions) and $search_carrierconditions != 'all') $sql .= " qc_reports.report_carrierconditions = '$search_carrierconditions' AND "; if (!empty($search_commodity) and $search_commodity != 'all') $sql .= " qc_lots.lot_commodity = '$search_commodity' AND "; if (!empty($search_inspectedby)) $sql .= " qc_reports.report_inspectedby = '$search_inspectedby' AND "; $sql = substr($sql, 0, -4); $query = mysql_query($sql); $numrows = mysql_num_rows($query); ?> RESULTS - <?php echo $numrows; ?> <hr> <table width='500'><tr><td><b>Date</b></td><td><b>Lot Number</b></td><td><b>PO</b></td><td> </td></tr> <tr> <td> </td> </tr> <?php while ($row = mysql_fetch_assoc($query)) { $id = stripslashes($row['id']); $report_lot_number = stripslashes($row['report_lot_number']); $report_po = stripslashes($row['report_po']); $report_date = stripslashes($row['report_date']); echo "<tr> <td>" . $report_date . "</td></td><td>" . $report_lot_number . "</td><td>" . $report_po . "</td><td><a href='view_report.php?id=" . $id . "'>View</a></td> </tr>"; } echo '</table><br><br><br><hr><br><br>'; } ?> All the variables are passed from a HTML form with $_POST. I need the search to work like this: If there is a value in a form field then the query gets appended with that value but when it gets to the $search_commodity it needs to search the second table (qc_lots) and check for the results. Any results that match have to be matched to the results from the first table (qc_reports) and display (echo) only qc_reports that match to both tables. The only common field is the report_id on the qc_lots table and the id on the qc_reports table. I'm stuck and need some guidance. Can someone help please? hi everybody simply love this forum because i always get the question perfectly answered. i am here this time with a rather complicated question: i am creating a simple duty plan for different departments for exeample department #1 is "Tech" and department #2 is "Service" different employees working in these departments change their dutys and will are sent to another department or section or go on holidays. this is why i have at least 4 different mysql tables to store the data:- personel(storing the personal information of the workers) dutyplan(storing the week's working daysy of the workers) departments(storing the starting and ending dates of the department change) vacation(stores the start and ending dates of the vacations) in all the tables the common id is the pid which is issued unique to every worker. i am still able to work only with the 1st two tables. i can edit and create new plans for the weeks for employees working in the departments with the following php code(submitting only to edit the plan) if i add a date range for example Monday the 24th of January to Sunday the 30th of January for an employee working in the Tech department to work a few days in service department, it will show the employee in the week on the plan of both departments. if both department heads edit the plan without communicating to each other, and knowing on which date the worker goes out and in to the department, the 1st one will plan him for the whole week on his dutyplan and the second department head will overwrite this plan(if edited) or if creating a new plan(create the duty of the worker also one more time). i want to avoid this confusion and manual work. the same is with the vacation or sickness tables, if the employee has vacation, the program should check and return the selected value in the pulldown menu with the value stored in the vacation or sickness tables appropriate to the date in the plan table. ************************************************************************ form.php: <? require "config.php"; $result=mysql_query("select * from personel, dutyplan, department, vacation WHERE personel.pid = dutyplan.pid and personel.pid = vacation.pid and dp.pid = departments.pid and departments.Section = 'Service' order by dp.id asc"); ?> <? while($row=mysql_fetch_assoc($result)){ ?> // after that i create table, displaying all the days of the week from monday to sunday and use this code <tr> <td><? echo $row['FirstName'] . " " . $row['LastName']; ?>: </td> <td> <select name="monday_<? echo $row['id']; ?>" id="select1"> <option><? echo $row['Mo']; ?></option> <option>Duty</option> <option>Free</option> <option>Vacation</option> //the same way down to sunday, for every day the different options to be selected. it displays the records perfectly, as long as there is no change of department planed and the vacation must also be selected manually. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ update.php <? if($_POST['Submit']){ require "includes/config.php"; $result=mysql_query("select * from dutyplan, departments, vacation order by dutyplan.id asc"); while($row=mysql_fetch_assoc($result)){ $mo=$_POST["monday_".$row[id]]; $tu=$_POST["tuesday_".$row[id]]; $we=$_POST["wednesday_".$row[id]]; $th=$_POST["thursday_".$row[id]]; $fr=$_POST["friday_".$row[id]]; $sa=$_POST["saturday_".$row[id]]; $su=$_POST["sunday_".$row[id]]; mysql_query("update dp set Mo='$mo', Tu='$tu', We='$we', Th='$th', Fr='$fr', Sa='$sa', Su='$su' where id='$row[id]'"); } echo "Records updated"; } ?> **************************************************** how would you gueys solve this problem? many thanks in advance Hi, So I'm trying to make a car rental project, and I need to show cars of a specific type, available in a specific period. I'm currently using this query: SELECT * FROM car, reservations WHERE car.car_id = reservations.car AND car.type = 1 AND reservations.reserved_from >= "2011-12-22" AND reservations.reserved_to <= "2012-12-20"; So this returns all the cars of the type 1 reserved in 2011-12-22 - 2012-12-20 period. So know that I know which cars are unavailable, how would you go ahead and pick out what's left? Not sure if this topic goes in here, it is related to PHP but also MySql, so if i'm on the wrong board sorry! What i'm trying to do is search for a keyword in 5 different tables and return the keyword ID from the table that its in The tables i'm trying to search are as follow location state county region continent The "location" table has all the locations i.e cities and each row has the following columns: id | continent_id | country_id | state_id | region_id | city_name The "state" table is set the the following: id | name "county" table : id | name "region" table: id | region and "continent" table id | name The way it works is the can search for any city or state or county or region or continent and ideally it should look into the five different tables and return the id of that table. So if the use searches for United States it will look for United States in all five tables, obviously it would find it in the "country" table so it should return that "id". The results are returned in "json format" Below is the code i have: Code: [Select] <? $input = $_GET['keyword']; $data = array(); /* In this query i'm attempting to search in all databases, but i'm not sure if i'm doing this right. I'm not getting any results so i know something is wrong just don't know how to write it. */ $query = mysql_query("SELECT * FROM locations JOIN states ON states.id = locations.state_id JOIN countries ON countries.id=locations.country_id JOIN regions ON regions.region_id = locations.region_id JOIN continents ON continents.id=locations.continent_id WHERE name LIKE '$input%' OR state LIKE '$input%' OR region LIKE '$input%' OR country LIKE '$input%' OR continent LIKE '$input%'") or die(mysql_error()); /* Here the values are added to to the $json array. The "value" should be the "id" from the table that the keyword matched. The 'name' Should be the name of the actual keyword. Again if they search for United States the "id" will come from the "countries" table and the "value" would come from the "countries" table as the name */ while ($row = mysql_fetch_assoc($query)) { $json = array(); $json['value'] = $row['id']; $json['name'] = $row['name']; $data[] = $json; } header("Content-type: application/json"); echo json_encode($data); ?> Any help would he be appreciated, i don't want people to do it for me, but rather just guide me a little bit. Back with a new problem. I have 8 tables interconnected. Table#1 - Users user_id | name Table#2 - user_categories id | user_id | category_id Table#3 - user_cities id | user_id | city_id Table#4 - user_dates id | user_id | dates_available Table#5 - categories category_id | category_name Table#6 - cities city_id | city_name Table#7 - provinces province_id | province_name Table#8 - categories country_id | country_name Each user will have multiple categories, cities and available dates listed in these tables. I simply want to retrieve and list each user and their data on a page. Here's my query. $url_city = 1; $url_category = 2; $url_date = '2021-07-19'; $find_records = $db->prepare("SELECT user_categories.*, categories.*, user_cities.*, cities.*, provinces.*, countries.*, user_dates.*, users.* FROM users LEFT JOIN user_categories ON users.user_id = user_categories.user_id LEFT JOIN user_cities ON users.user_id = user_cities.user_id LEFT JOIN user_dates ON users.user_id = user_dates.user_id LEFT JOIN categories ON user_categories.category_id = user_categories.category_id LEFT JOIN cities ON user_cities.city_id = cities.city_id LEFT JOIN provinces ON cities.province_id = provinces.province_id LEFT JOIN countries ON provinces.country_id = countries.country_id WHERE user_cities.city_id = :city_id AND user_categories.category_id = :category_id AND user_dates.date_available = :date_available GROUP BY users.user_id"); $find_records->bindParam(':city_id', $url_city); $find_records->bindParam(':category_id', $url_category); $find_records->bindParam(':date_available', $url_date); $find_records->execute(); $result_records = $find_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0) { foreach($result_records as $row) { $user_id = $row['user_id']; $name = $row['name']; $country_id = $row['country_id']; $country_code = $row['country_code']; $country_name = $row['country_name']; $province_id = $row['province_id']; $province_code = $row['province_code']; $province_name = $row['province_name']; $city_id = $row['city_id']; $city_name = $row['city_name']; $category_id = $row['category_id']; $category_name = $row['category_name']; } } There are no errors but the above query would only return a single row with only 1 "user" despite having multiple users in the "users" table. If I remove the GROUP BY, then it'll return multiple rows of the same user instead of all the relevant users. So what do you think I am doing wrong with my query? Edited July 20 by imgroootOk, so I've spent quite a bit of time piecing together this solution from a variety of sources. As such, I may have something in my code below that doesn't make sense or isn't neccessary. Please let me know if that is the case. I'm creating an administrative form that users will you to add/remove items from a MySQL table that lists open positions for a facility. The foreach loop generates all of the possible job specialties from a table called 'specialty_list'. This table is joined to a second table ('open_positions') that lists any positions that have been selected previously. Where I'm stuck is getting the checkbox to be checked if the facility_ID from the open_positions table matches the $id passed in the URL via ?facility_id=''. Here's where I am so far: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($results)) { $positions[$row['specialty_shortname']] = $row['specialty_displayname']; } echo "<form method='POST' action='checkbox.php'>"; foreach($positions as $specialty_shortname => $specialty_displayname) { $facility_ID = $row['facility_ID']; $checked = $facility_ID == $row['facility_ID'] ? ' checked' : ''; echo "<input type='checkbox' name='position[]' value=\"{$specialty_shortname}\"{$checked}> {$specialty_displayname}</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; Any ideas how to get this working? I feel like I'm very close, but I just can't get it. I also tried starting from scratch with a WHILE statement instead of a FOREACH, but haven't tweaked it enough to prevent duplicate checkboxes. With that in mind, here it is, just in case that's a better direction: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); echo "<form method='POST' action='checkbox.php'>"; while($row=mysql_fetch_assoc($results)) { $facility_ID = $row['facility_ID']; $specialty_shortname = $row['specialty_shortname']; $specialty_displayname = $row['specialty_displayname']; if ($facililty_ID==$id) { $checked=' checked'; } echo "<input type='checkbox' name='position[]' value=\"$specialty_shortname\"$checked> $specialty_displayname</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; How do I get LIKE to check multiple values? It works if you type in a single word, but not multiple, which I want it to in order to get an accurate search result. Here is what I am trying to do: $target = "siemens 6s" ; $multis = explode(" ", $target) ; $query = "SELECT parts_table.*, manufacturers.* FROM parts_table, manufacturers WHERE parts_table.ManufacturerID = manufacturers.ManufacturerID AND parts_table.PartNumber LIKE" ; foreach($multis as $current) { $queryext .= " '%$current%' OR" ; } $queryext = substr($queryext, 0, -3) ; // Remove the last 4 charecters i.e. " AND". $query .= $queryext ; echo $query .= " OR manufacturers.ManufacturerID = parts_table.ManufacturerID AND manufacturers.ManufacturerName LIKE" . $queryext ; include("dbconnect.php") ; $result = mysql_query($query) ; while($row = mysql_fetch_assoc($result)){ echo $row['ManufacturerName'] ; echo $row['PartNumber'] ; } I've looked around at a bunch of sample code and cannot seem to get this to work. I'm trying to create a table with the values provided in a form along with an uploaded image. Here is what I have. Code: [Select] <?php //Set variables from form $title = $_POST["title_textfield"]; $description = $_POST["description_textbox"]; $price = $_POST["price_textfield"]; $time = date("ymdHis"); $me = $myuserID /Create Table $con = mysql_connect("mydatabase.mysql.com","databaseAdmin","Adminpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } //check if table exists // Create table $time = date("ymdHis"); $tablename = "1_$me$time"; mysql_select_db("db_01", $con); $sql = "CREATE TABLE $tablename ( ID int NOT NULL AUTO_INCREMENT, imageData LONGBLOB NOT NULL , PRIMARY KEY(comicID), Owner varchar(15), Status varchar(15), AgeRestriction varchar(25), Title varchar(25), Description varchar(100), Price varchar(15) )"; // Execute query mysql_query($sql,$con); //input info into table mysql_query("INSERT INTO $tablename (Owner, Status, Title, Description, Price) VALUES ('$myid', 'Pending', '$title', '$description', '$price')"); //Image control!!!! $maxFileSize = "2000000"; // 2 MB file size //Initializing the image types. $image_array = array("image/jpeg","image/jpg","image/gif","image/bmp","image/pjpeg","image/png"); // valid image type //store the file type of the uploading file. $fileType = $_FILES['userfile']['type']; $nname= $_FILES['userfile']['name']; echo "$nname"; //Initializing the msg variable. Although , not necessary. $msg = ""; // if Submit button is clicked if(@$_POST['Submit']) { // check for the image type , before uploading if (in_array($fileType, $image_array)) { // check whether the file is uploaded if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check whether the file size is below 2 mb if($_FILES['userfile']['size'] < $maxFileSize) { // reading the image data $imageData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // inserting into the database $sql = "INSERT INTO $tablename (imageData) VALUES ('$imageData')"; mysql_query($sql) or die(mysql_error()); $msg = " Data successfully uploaded"; } else { $msg = " Error : File size exceeds the maximum limit "; } } } else { $msg = "Error: Not a valid image "; } } mysql_close($con); ?> All the fields populate just fine except the imageData field which shows "[BLOB - 0 Bytes]" Any help would be GREATLY appreciated. Thank you for even taking the time to look. Cordially, TcS Hi all How do I modify the below code to search multiple tables in mySQL database? $query = "select * from store_items where description like \"%$trimmed%\" or title like \"%$trimmed%\" or dimensions like \"%$trimmed%\" order by id ASC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); It is for a search function and I need it to search another table called 'about_text' and 'faq_text' Thanks Pete How do I total unique id's with php or MySQL. For instance in MySQL I have... ID 1 1 3 4 2 1 1 3 How can I total all of the 1's, all of the twos, all of the threes and so forth. I have four 1's, one 2, two 3's and so forth... Hi friends, I'm looking to try and echo the profits from a MySQL "totals" table for each month of the year... the table bascically consists of a "totals" column which contains the total amount spent on each order, a "suppliertotals" column which contains the total amount that it costs us to buy the goods for that order and an "orderdate" column which stores the order date as "d/m/y" (so 01/01/01). To work out the total margin from the complete table, I calculate the sum of totals minus the sum of suppliertotals. This is our margin. I'm currently doing the calculation with MySQL's sum() function, and using PHP explode to get the date, but I'm obviously doing something wrong since PHP is returning the same month several times with different amounts... Let me show you the code I have; I presume I need to use some kind of foreach statement, but I'm not sure where or how... hoping you can help! if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("onetelec_wsshop", $con); $result=mysql_query("SELECT orderdate FROM totals", $con); while($row = mysql_fetch_array($result)) { $ordmonth = explode("/", $row['orderdate']); $ordmonth = $ordmonth[1]; switch ($ordmonth) { case "01": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for January<br /><br />"; break; case "02": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for February<br /><br />"; break; case "03": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for March<br /><br />"; break; case "04": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for April<br /><br />"; break; case "05": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for May<br /><br />"; break; case "06": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for June<br /><br />"; break; case "07": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for July<br /><br />"; break; case "08": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for August<br /><br />"; break; case "09": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin = $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for September<br /><br />"; break; case "10": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin += $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for October<br /><br />"; break; case "11": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin += $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for November<br /><br />"; break; case "12": $stresult=mysql_query("SELECT sum(total), sum(stotal) FROM totals WHERE ordate LIKE '%/$ordmonth/%'", $con); while($strow = mysql_fetch_array($stresult)) { $margin += $strow['sum(total)'] - $strow['sum(stotal)']; } echo $margin." for December<br /><br />"; break; } } This portion is kind of stumping me. Basically, I have a two tables in this DB: users and users_access_level (Separated for DB normalization) users: id / username / password / realname / access_level users_access_level: access_level / access_name What I'm trying to do, is echo the data onto an HTML table that displays users.username in one table data and then uses the users.access_level to find users_access_level.access_name and echo into the following table data, I would prefer not to use multiple queries if possible or nested queries. Example row for users: 1234 / tmac / password / tmac / 99 Example row for users_access_level: 99 / Admin Using the examples above, I would want the output to appear as such: Username: Access Name: Tmac Admin I am not 100% sure where to start with this, but I pick up quickly, I just need a nudge in the right direction. The code I attempted to create just shows my lack of knowledge of joining tables, but I'll post it if you want to see that I did at least make an effort to code this myself. Thanks for reading! I create a post just now but cannot seem to find it to add to it. Anyhow, I have 2 tables, I need to multiply qty from the one table to the mass from the other to get a total, which I have achieved with this code: $sql_total_mass = " SELECT jobs_assembly.assemble_qty, jobs.mass, (jobs_assembly.assemble_qty * jobs.mass) AS 'sum' FROM jobs_assembly LEFT JOIN jobs on jobs_assembly.jobs_id = jobs.id LEFT JOIN job_names ON jobs.job_names_id = job_names.job_id WHERE jobs_assembly.assemble_date = '$link_date' ORDER BY job_names.job_name, jobs.assembly "; $result_total_mass = mysqli_query($conn, $sql_total_mass); if (mysqli_num_rows($result_total_mass) > 0) { while($row_total_mass = mysqli_fetch_assoc($result_total_mass)) { echo $row_total_mass['sum'].'<br />'; } //while } //if Now I need to take all these totals and make a grand total. So basically add all the results from $row_total_mass[‘sum’] together and show it.
I have a form where a user can duplicate part of a form like below: I've named the fields with the HTML arrays (ie. "fieldName[]") and came up with this: //--> CONTROLLERS $system_controllers_qty = $_POST['system_controllers_qty']; $system_controllers_make = $_POST['system_controllers_make']; $system_controllers_model = $_POST['system_controllers_model']; $system_controllers_serial_no = $_POST['system_controllers_serial_no']; for ($i = 0; $i < count($system_controllers_qty); $i++) { echo "qty " . clean($system_controllers_qty[$i]) . "<br/>"; echo "make " . clean($system_controllers_make[$i]) . "<br/>"; echo "model " . clean($system_controllers_model[$i]) . "<br/>"; echo "serial_no " . clean($system_controllers_serial_no[$i]) . "<br/>"; } //--> CPUS $system_cpus_qty = $_POST['system_cpus_qty']; $system_cpus_model = $_POST['system_cpus_model']; $system_cpus_serial_no = $_POST['system_cpus_serial_no']; $system_cpus_speed = $_POST['system_cpus_speed']; for ($i = 0; $i < count($system_cpus_qty); $i++) { echo "qty " . clean($system_cpus_qty[$i]) . "<br/>"; echo "model " . clean($system_cpus_model[$i]) . "<br/>"; echo "serial_no " . clean($system_cpus_serial_no[$i]) . "<br/>"; echo "speed " . clean($system_cpus_speed[$i]) . "<br/>"; } //--> DISKS $system_disks_qty = $_POST['system_disks_qty']; $system_disks_make = $_POST['system_disks_make']; $system_disks_model_no = $_POST['system_disks_model_no']; $system_disks_size = $_POST['system_disks_size']; $system_disks_serial_no = $_POST['system_disks_serial_no']; for ($i = 0; $i < count($system_disks_qty); $i++) { echo "qty " . clean($system_disks_qty[$i]) . "<br/>"; echo "make " . clean($system_disks_make[$i]) . "<br/>"; echo "model_no " . clean($system_disks_model_no[$i]) . "<br/>"; echo "size " . clean($system_disks_size[$i]) . "<br/>"; echo "serial_no " . clean($system_disks_serial_no[$i]) . "<br/>"; } //--> MEMORY $system_memory_qty = $_POST['system_memory_qty']; $system_memory_serial_no = $_POST['system_memory_serial_no']; $system_memory_manf = $_POST['system_memory_manf']; $system_memory_part_no = $_POST['system_memory_part_no']; $system_memory_size = $_POST['system_memory_size']; for ($i = 0; $i < count($system_memory_qty); $i++) { echo "qty " . clean($system_memory_qty[$i]) . "<br/>"; echo "serial " . clean($system_memory_serial_no[$i]) . "<br/>"; echo "manf " . clean($system_memory_manf[$i]) . "<br/>"; echo "part_no " . clean($system_memory_part_no[$i]) . "<br/>"; echo "size " . clean($system_memory_size[$i]) . "<br/>"; } This just outputs all the fields I post at the moment. Say I have 3 different disk types, it's going to loop 3 times. Is it possible to make this all into 1 giant query or am I better off doing each query separately? Each section is a different table. I have a search where I want to be able to search a string of words. The search is going to be looking in 2 different table joined by a left outer join. The tables are "quotes" and "categories". $sql="SELECT q.id, q.username, q.quote, q.by, q.voteup, q.votedown, q.servtime, c.quote_id, c.label FROM quotes q LEFT OUTER JOIN categories c ON q.id = c.quote_id WHERE ( q.username LIKE '$srch' OR q.quote LIKE '$srch' OR q.`by` LIKE '$srch' OR c.label LIKE '$srch')"; The above mysql statement works and returns values..BUT if say, I search "john" and "funny", and a quote is posted by the user "john", but has a category of "funny" it will output the same quote twice. I was wondering if there was a way to see if a quote has either 1 term or both terms, if so display that quote but only display it once. Below is what the query is outputting. [100] => Array ( [id] => 100 [username] => John [quote] => new test quote blah blah [by] => John [voteup] => 0 [votedown] => 0 [servtime] => 2010-12-02 @ 16:27:03 [label] => Array ( [0] => Historic [1] => Serious [2] => Funny ) ) Here is the code in full. //// $sword = explode(" ",$search); foreach($sword as $sterm){ $srch="%".$sterm."%"; echo"$srch<br />"; $sql="SELECT q.id, q.username, q.quote, q.by, q.voteup, q.votedown, q.servtime, c.quote_id, c.label FROM quotes q LEFT OUTER JOIN categories c ON q.id = c.quote_id WHERE ( q.username LIKE '$srch' OR q.quote LIKE '$srch' OR q.`by` LIKE '$srch' OR c.label LIKE '$srch')"; $result=mysql_query($sql); while($row=mysql_fetch_object($result)){ $quote[$row->id]['id'] = $row->id; $quote[$row->id]['username'] = $row->username; $quote[$row->id]['quote'] = $row->quote; $quote[$row->id]['by'] = $row->by; $quote[$row->id]['voteup'] = $row->voteup; $quote[$row->id]['votedown'] = $row->votedown; $quote[$row->id]['servtime'] = $row->servtime; $quote[$row->id]['label'][] = $row->label; } echo"<pre>"; print_r($quote); echo"</pre>"; I don't think this is the fastest way of doing this, as it loops for each item in the db, per each keyword that is search. Any help would be great!! -BaSk I am trying to export multiple csv files to download from 2 separate tables in my database. Some background: I have a web app that links to a phpmyadmin database. There are 2 tables in the database (entering and exiting). These tables hold the phone inventory information of employees currently entering or exiting the organization. The fields in my tables a location, firstname, lastname, username, extension, mac, type What I am trying to do is export the data in these 2 tables to CSV (which I have working now) but I need to have multiple CSVs for each. For example, for my exiting table, I need to have one CSV export all the fields in the table and I also need another CSV to export just the location and username field. I have a simple html form with a submit button which is currently working now: <form action="exportexiting.php" method="POST" style="width: 456px; height: 157px"> <div> <fieldset> <legend style="width: 102px; height: 25px"><strong>Entering CSV:</strong></legend> <input name="Export" type="submit" id="Export" value="Export"> </fieldset><br/> </div> </form> This links to my exportexiting.php file: <?php $host = 'localhost'; $user = 'root'; $pass = 'xxxx'; $db = 'PhoneInventory'; $table = 'exiting'; // Connect to the database $link = mysql_connect($host, $user, $pass); mysql_select_db($db); require 'exportcsv.inc.php'; exportMysqlToCsv($table); ?> Then to exportcsv.inc.php: <?php function exportMysqlToCsv($table,$filename = 'export.csv') { $csv_terminated = "\n"; $csv_separator = ","; $csv_enclosed = ''; $csv_escaped = "\\"; $sql_query = "select * from $table"; // Gets the data from the database $result = mysql_query($sql_query); $fields_cnt = mysql_num_fields($result); $schema_insert = ''; for ($i = 0; $i < $fields_cnt; $i++) { $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed; $schema_insert .= $l; $schema_insert .= $csv_separator; } // end for $out = trim(substr($schema_insert, 0, -1)); $out .= $csv_terminated; // Format the data while ($row = mysql_fetch_array($result)) { $schema_insert = ''; for ($j = 0; $j < $fields_cnt; $j++) { if ($row[$j] == '0' || $row[$j] != '') { if ($csv_enclosed == '') { $schema_insert .= $row[$j]; } else { $schema_insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed; } } else { $schema_insert .= ''; } if ($j < $fields_cnt - 1) { $schema_insert .= $csv_separator; } } // end for $out .= $schema_insert; $out .= $csv_terminated; } // end while header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Length: " . strlen($out)); // Output to browser with appropriate mime type, you choose header("Content-type: text/x-csv"); //header("Content-type: text/csv"); //header("Content-type: application/csv"); header("Content-Disposition: attachment; filename=$filename"); echo $out; exit; } ?> Again, this is working perfectly for only exporting all the data from the exiting table into one CSV file. My question is, how can I make my one submit button export the 2 CSV files that I need? Thanks for the help... Dear all, I would like to find the total number of individual record in MySQL with php. For example: I have different department name stored in a column in MySQL. I would like to find out the total number of each department. But I do not know the names of the department How can I do it?? Counting the total of each department without knowing their names Thanks! LOL note the topic is a pun at Help Vampires... I actually have an unchallenging question. I'm trying to echo out a column in a MySQL table. I'm getting one field echoing, but not the others: I'm using this code style, but I've made a small mistake somewhere at the end, I've tried many combinations trying to fix it, but haven't succeeded.. $query = "select email from newsletters"; $result = mysql_query($query); $row = mysql_fetch_array($result); foreach ($row as $email) {echo $email;} I got the argument foreach() straight out of the manual and copied the syntax style exactly as was demonstrated in the example, but its still not working. What have I done wrong? |