Lately i have been working on a form with which a user can select a checkbox and as a result of the selection it shows the database information in a table.
I browsed the stackoverflow questions and found a question that was almost the same, namely: Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked
So with this information, and some other information from the web, i started to create my code. Though after completion i had several errors, namely my database fields were duplicate on output, the data that the field had isn't outputted and there were two warnings. After a lot of searching and editing/trying i couldn't find the right solution so hence me asking this question in here.
Before i display my code i first give some information about the checkboxes, database and table/fields (and a (small) note: it is a wordpress database).
I have 1 database called xxx_wp1. THis database contains various (wordpress) table's but the table i want to retrieve information from is called: wp_participants_database.
This table contains various columns (around 15). Though, for this testing example i used just 3 of the 15 columns named: authorss, research_source and research_title. I inserted some random information (3 rows) in these 3 columns.
The form i created has, kinda obviously, 3 checkboxes for each column (so 1 for authors, research source and title).
Based on the previous link and some wordpress information i started to create my code for the selection, it is as follows:
<form method="post">
<input type="checkbox" name="columns[]" value="1" /><label for="Authors">Authors</label><br />
<input type="checkbox" name="columns[]" value="2" /><label for="Research Source">Research Source</label><br />
<input type="checkbox" name="columns[]" value="3" /><label for="Research Title">Research Title</label><br />
<input type="submit" name="go" value="Submit"/>
</form>
<?php
$all = false;
$column_names = array('1' => 'Authors', '2'=>'Research Source', '3'=>'Research Title');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
?>
<?php
mysql_close();
?>
As you can see, the quesry is a bit different because it has to connect to the Wordpress database (the global $wpdb and $wpdb->get_results). While typing this im thinking that this might also be part of the problem as this get_results is already getting results which i am also getting later on?
Anyway, while testing this i get a few errors / misbehavior which i cant seem to figure out.
The first errors are the following warnings:
- Warning: mysql_query() expects parameter 1 to be string, array given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 32 --- which is this line of code: `$result = mysql_query($tmp);`
- Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 43 --- which is this line of code: `while( $row = mysql_fetch_assoc($result))`
The second problem is that all of the columns are echo'd TWICE even before submitting. So this would mean this line of code is being done no matter what:
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
When i check a option and press the submit button, the right column is being showed (so yay that works), though all the 3 columns are still being showed (no matter what) as well as the selected one, so i got this if i select the first option:
authorss research_source research_title Authors (notice the first 3 are from my defined while the last one is from my defined $column_names.
The last problem is that the field values of the columns isn't being showed, the columns are just empty.
So the question is of anybody could give me some pointers about what is going wrong.
Thank you in advance!
*****UPDATE*****
I made some adjusting with the help of #Zeusarm
So firstly i changed the warnings (among others the $wpdb->get_results is changed to $wpdb->query) and the warnings are all gone. For some reason i gave the $array_names just their front-end names (stupid me), so i changed it, like you suggested to the proper column names as they are in the database table. So field 1,2,3 became: authors, research_source and research_title.
I also added the other changes. Although the errors are all gone, i still get all 3 the columns showed + 1 duplicate (depending on the number of checkboxes selected). Plus i still don't get the database data which is stored in the columns (for example: authorss has the following stored values in it: Barry, Henk and Nicolas.).
The code now looks like (with the form left out as it remained the same):
<?php
$all = false;
$column_names = array('1' => 'authorss', '2' => 'research_source', '3' => 'research_title');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->query( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
}
?>
<?php
mysql_close();
?>
*****UPDATE 2*****
So i changed the code and finally i am retrieving the data of the database! So i guess i should just work with the wordpress get_results for querying from now on.
Although i am retrieving the information i still have duplicates. When i go to the page, at first i have all 3 duplicates and the data retrieving is being output in the first 3 columns. When i select 1 checkbox option, the correct data of that checkbox is being displayed and the other data from the other checkboxes isn't (so that works). Though, for example when i only choose the authors checkbox, the data of authors is being displayed in the first authors checkbox and only 1 duplicate (namely 'authors') is being showed. Though when i click only the second checkbox, research source (column research_source) then the data of that column is only being showed (what is correct) BUT that data is being output in thew first authors column and again, 1 duplicate with the correct column name namely 'research_source'.
But because a picture says more than a 1000 words, i added some images to clear it up. (sorry for the links to the pictures but missing 2 reputation to post pics directly)
The starting columns/page (untouched):
Only authors selected and submitted:
Left this one out as i can also only upload 2 links withh less than 10 rep...
Only Research Source selected and submitted:
I see at least 2 errors in your code.
the $column_names associative array values are supposed to be passed as field names, so I assume that they are not correct, as you have spaces in them (and as I know wordpress by default does not have such field names.
if some selection is provided by user you are adding some extra field names to the once which are passed by user and you have a colon after them so it will generate an error.
I would rewrite the code like this
<?php
$all = false;
$column_names = array('1' => '`field1`', '2' => '`field2`', '3' => '`field3`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
Also as you have said $wpdb->get_results returns already the results - array so that's why you get the errors. Plus before calling mysql_fetch_assoc it is better to check if the passed parameter is recource and if the number of rows is not 0.
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
...
}
}
*********** UPDATE ***********
according to last changes try this code:
<?php
$all = false;
$column_names = array('1' => '`authorss`', '2' => '`research_source`', '3' => '`research_title`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
} else {
$all = true;
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
}
echo '</table>';
?>
Related
The code below is to display the quiz(questions and answers)
When submitting, I am getting error:
"Array ( ['1'] => 1 ) 1
Notice: Undefined offset: 1 in C:\xampp\htdocs\HR\functions\functions_applicants.php on line 152
2".
<form method="post" action="index.php?results">
<?php
for($i=1; $i<27; $i++) {
$query = query("SELECT * FROM assess_questions WHERE question_id =$i");
confirm($query);
while($row = fetch_array($query)) {
?>
<div>
<h4><?php echo $row['question']; ?></h4>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=1><?php echo $row['A']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=2><?php echo $row['B']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=3><?php echo $row['C']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=4><?php echo $row['D']; ?><hr>
</div>
<?php
}
}
?>
<input class="btn btn-info" type="submit" name="submit_answers"
value="Next">
</form>
THIS IS THE FUNCTION TO CHECK FOR THE ANSWER. THIS IS WHERE IM GETTING THE ERROR FROM. ITS THE $i that's causing the error.
if(isset($_POST['submit_answers'])) {
$result = 0;
$i = 1;
$average = 0;
$item = ($_POST['quizcheck']);
print_r($item) ;
$query = query("SELECT * FROM assess_questions");
confirm($query);
while($row = fetch_array($query)) {
print_r($row['answer_id']);
$checked = ($row['answer_id']) == $item[$i];
if($checked) {
$result++;
}
$i++;
}
}
The clue is in the contents of $item which you have done a print_r on and got the result:
Array(['1'] => 1)
You're getting this result because in your html your radio buttons are labelled quizcheck['n'] where n is the question id. So presumably in this case you have pressed the first radio button in the first question. You should change the line which gives the radio buttons a name to
<input type="radio" name="quizcheck[<?php echo $row['question_id']; ?>]" value=1><?php echo $row['A']; ?><br>
(i.e. remove the single quotes around <?php echo $row['question_id']; ?>). This will make $item look like:
Array ( [1] => 1 )
so the test
($row['answer_id']) == $item[$i];
will work. Note the parentheses around $row['answer_id'] are unnecessary.
The other issue you are going to run into is that your form obviously doesn't require the user to submit an answer to every question. This means that in your while loop you need to check whether the user has submitted an answer to be checked against the result. If you are not going to make it compulsory to answer all questions, you will need to put an array_key_exists check around the result checking code:
if (array_key_exists($i, $item)) {
$checked = $row['answer_id'] == $item[$i];
if ($checked) {
$result++;
}
}
you begin with $i = 1;
in which case you'll avoid $item[0]; (first position) and it will mismatch $checked = ($row['answer_id']).
start with $i=0; as if there's only one answer $i[1] will not exists but $i[0];
****EDIT****
first check your query result for not being void:
example, having this db connection function/method:
<?php
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli($host, $user, $passwd, $dbName);
return $mysqli;
}catch (Exception $mysqlin){
echo "Error establishing connection with ddbb ".$mysqlin->getMessage();
}
}
?>
And modifying your code:
if(isset($_POST['submit_answers'])) {
$result = 0;
//indexes must start at 0 unless you ensure that you don't need 0 value and your algorithm will not keep trying to get a value out of bounds / array offset
$i = 0;
$average = 0;
//i assume that $_POST['quizcheck'] is an array, otherwise the $item[$i] will be an out of bounds, which match with your issue (array offset). But i ensured some parts of your structure below for you to learn:
$item = ($_POST['quizcheck']);
print_r($item) ;
//you'll must prepare this statement after, for security
$sql = query("SELECT * FROM assess_questions");
//we get the result of this query on $result, if possible
if($result = connection()->query($sql)){
//we get the first row inside $rs (usually called Record Set) as associative (it means that you'll call the values as the column name on DB unless you use AS "Alias" on your query.
$rs = mysqli_fetch_assoc($result);
//if the record set is not void:
while($rs!="") {
//assuming that your DB col is called answer_id
print_r($rs['answer_id']);
//checked will get the value of matching those two arrays, so make sure you control nullables:
if($checked = ($rs['answer_id']) == $item[$i]){
//only if $checked value could be set
if($checked) {
$result++;
}
}
$i++;
}
//repeat this to get the next value, when it has no more values it will be void so it will escape from while loop.
$rs = mysqli_fetch_assoc($result);
}
}
Never assume that you'll get always a value.
Never assume that users will put numbers in some input only because you told them to do it.
Never use dates without checking.
Never state an algorithm with not-controlled vars/function outputs.
Control all data all over across your code and comment it, it will help you to avoid issues and modify your code months after you coded it.
Hope it helps you.
I recommend you to get a hosting to test/code in a controlled environment.
My form have multiple checkboxes in it (each with the code):
<input type="checkbox" name="id[]" value="<? echo $row['id'] ?>">
when user select id = 2 , 3 and 9 and submit the value. In my update php i am using following code to get selected value
echo "Check box test<pre>" ;
print_r($id);
echo "</pre>";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $check) {
echo $check."\n";
}
}
// update data in mysql database
$sql="UPDATE table SET display = '2' WHERE id IN ($check)";
i am always getting last selected id updated like 9
but i am not getting result as i wanted like
$sql="UPDATE table SET display = '2' WHERE id IN (2,3,9)";
. please Help what to do. i am very new to php.
You are doing nothing with $check, Make id like this
$ids="";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $id) {
$ids[] = $id;
}
}
$check = implode(",", $ids);
Because you are iterating the loop and $check will have latest value for the iteration.
foreach($_POST['id'] as $check) {
echo $check."\n";
}
Why can't you try instead ?
$check[] = $_POST['id'];
I think you need to get a better understanding of echo and the diference between server-side and client-side.
What you are looking for is implode
if(!empty($_POST['id'])){
$check = '(' . implode(',', $_POST['id']) . ')';
}
here's my problem:
I have a form in which user inputs 3 things (ID key, Date from and Date To) and also from a group o checkboxes he chooses which columns he wants to see in the result. (the form is way to big because its database table has about 15 columns each, so I don't post it here)
here is the (part of the) code which handles these inputs and generates the query. (I'll explain after it what exactly does)
<?php
//Check the columns that should be shown in the table
if(empty($_POST['vesselcolumns']) && empty($_POST['expeditioncolumns'])){
$columns='*';
}else if (isset($_POST['vesselcolumns']) || isset($_POST['expeditioncolumns'])) {
if (empty($_POST['vesselcolumns'])){
$columns='';
}else{
$vesselcolumns= implode(',', $_POST['vesselcolumns']);
$columns=$vesselcolumns;
}
if (empty($_POST['expeditioncolumns'])){
$columns.='';
}else{
$expeditioncolumns = implode(',', $_POST['expeditioncolumns']);
if($columns!=''){
$columns.=','.$expeditioncolumns;
}
}
}
//AMAS check
if(empty($_POST['searchv'])){
echo 'No AMAS given, will print ALL expedition data<br />';
}else{
$amas = $_POST['searchv'];
}
//Deploy Date FROM and TO check
if(empty($_POST['deploydatefrom'])){
$datefrom = '0000-00-00';
}else{
$datefrom = $_POST['deploydatefrom'];
}
if(empty($_POST['deploydateto'])){
$dateto = '9999-12-31';
}else{
$dateto = $_POST['deploydateto'];
}
if(isset($amas)){
$expeditionq="SELECT '$columns'
FROM vessel
INNER JOIN vessel_expeditions
ON vessel.AMAS=vessel_expeditions.vexpedition_AMAS AND vessel.AMAS= '$amas'
INNER JOIN expedition
ON vessel_expeditions.expedition_ID=expedition.expedition_ID
WHERE expedition.deployDate >= '$datefrom' AND expedition.deployDate <= '$dateto'";
$result=mysqli_query($con,$expeditionq);
if($columns=='*'){
$takefields=mysqli_query($con, "SHOW COLUMNS FROM vessel");
while ($vcol = mysqli_fetch_array($takefields)){
$vcolu= array( $vcol['Field']);
}
$takefieldse=mysqli_query($con, "SHOW COLUMNS FROM expedition");
while ($ecol = mysqli_fetch_array($takefieldse)){
$ecolu= array($ecol['Field']);
}
$vccounter = count($vcolu);
$eccounter = count($ecolu);
while($row = mysqli_fetch_array($result)){
for($i=0; $i<$vccounter; $i++){
echo $row[$vcolu[$i]] . '<br />';
}
for($i=0; $i<$eccounter; $i++){
echo $row[$ecolu[$i]] . '<br />';
}
}
}else{
$column = explode(',', $columns);
$counter = count($column);
$forexport='<table id="results">
<tr>';
for($i=0; $i<$counter; $i++){
$forexport .= '<th>' . $column[$i] . '</th>';
}
$forexport.='</tr>';
while($row = mysqli_fetch_array($result)){
for($i=0; $i<=$counter; $i++){
$forexport .= '<td>' . $row[$column[$i]] . '</td>';
}
$forexport.='</tr>';
}
$forexport .='</table>';
echo $forexport;
echo '<form name="exportanalysis" method="post" action="exportanalysis.php">
<input type="hidden" name="export" value="' . htmlspecialchars($forexport, ENT_QUOTES) . '" />
<label for="selectcsv"><img src="img/csv-icon.png" width="50" height="50" /> </label>
<input type="radio" name="filexport" value="csv" id="selectcsv" required />
<label for="selectxls"><img src="img/xls-icon.png" width="50" height="50" /> </label>
<input type="radio" name="filexport" value="xls" id="selectxls" />
<input type="submit" value="Download" />';
}
}else{
echo 'amas not set';
}
?>
First I check which columns has user selected (if none selected I put "*") and I break them in an array with implode (as from the checkboxes they come in string like this: column1,column2,column4, etc.).
Then I check the AMAS (which is the ID key user inputs) and finally I check the dates if given [strange thing here when I submitted the form without date values with isset() even though there was no value in them it kept passing the if(as they were set) so I changed it to empty()].
After multiple tests I've found out that the query ($expeditionq) works fine (I even tested it in MySQL directly). Also the "SHOW COLUMNS" queries work fine and I fetch their results and showed them.
The problem comes when I'm trying to show the results of the $expeditionq query and I assume that the problem is this: $row[$column[$i]] but I cannot figure out another way to do it :/
Puh. Sorry this code looks weired. Is this what you want to express:
if(!empty($_POST['vesselcolumns']) && !empty($_POST['expeditioncolumns'])){
$columns= implode(',', $_POST['vesselcolumns']) . ',' . implode(',', $_POST['expeditioncolumns']);
}
else if(!empty($_POST['vesselcolumns'])) {
$columns= implode(',', $_POST['vesselcolumns']);
}
else if(!empty($_POST['expeditioncolumns'])) {
$columns= implode(',', $_POST['expeditioncolumns'])
}
else {
$columns='*';
}
Anyway, the problem is just obvious:
SHOW COLUMNS will return all columns in that table.
You iterating over the result, which contains only the columns the user selected.
So you are trying to access alphanumeric indexes or "keys" within the row that dont exist unless the user has requested to show all columns.
EDIT: Sorry, this was an incomplete reading due to the unstructured way the source is organized. The query SHOW COLUMNS is only executed, when $columns == "*", so all fields are selected obviously.
I'm populating the select boxes with data from my database. (sql server 2008).
Here is my function:
function sample_items($product_types = array('METER KIT', 'TEST STRIP', 'LANCET', 'CONTROL SOLUTION', 'LANCING DEVICE', 'BATTERY', 'MISC'))
{
$a = array();
$i = 0;
$def = $product_types;
foreach($product_types as $k)
{
$qty = sql::one_row("select min_, max_, interval from event.dbo.product_type where product_type = " . hexstr($k));
$label = str_replace('CONTROL SOLUTION', 'C/S', $k);
$label = str_replace('LANCING DEVICE', 'L/D', $label);
$a[] = input_check("items[ok][$i]")->label($label);
if ($k == 'TEST STRIP')
{
$a[] = input_select("items[ptcode][$i]", sql::two_column_array("select rtrim(a.CODE_), case when B.id IS NULL THEN rtrim(a.DESCRIPTION_) else 'BACKORDER:'+RTRIM(a.DESCRIPTION_) end
from PACWARE.ADS.PTDME a left outer join event.dbo.backorder b on a.CODE_=b.ptcode where a.MEDICAREID = 'SAMP' and a.DESCRIPTION_ like '%STRIP%'"), 1)->label('')->same_line()->set_class('wide2');
}
else if ($k == 'LANCET')
{
$a[] = input_select("items[ptcode][$i]", sql::two_column_array("select rtrim(a.CODE_), case when B.id IS NULL THEN rtrim(a.DESCRIPTION_) else 'BACKORDER:'+RTRIM(a.DESCRIPTION_) end
from PACWARE.ADS.PTDME a left outer join event.dbo.backorder b on a.CODE_=b.ptcode where a.MEDICAREID = 'SAMP' and a.DESCRIPTION_ like '%LANCET%'"), 1)->label('')->same_line()->set_class('wide2');
}
else if ($k == 'MISC')
{
$a[] = input_select("items[ptcode][$i]", \Ptdme::items_by_product_type(array('SAMPLE PRODUCT','MISCELLANEOUS SUPPLIES')), 1)->label('')->same_line()->set_class('wide2');
}
else { $a[] = input_select("items[ptcode][$i]", \Ptdme::items_by_product_type($k), 1)->label('')->same_line()->set_class('wide2'); }
if (!empty($qty)) $a[] = input_select("items[qty][$i]", range($qty['min_'], $qty['max_'], $qty['interval']))->label();
else $a[] = input_select("items[qty][$i]", range(0, 100))->label();
$i++;
}
return input_group('Items', $a)->whole();
}
It's housed in an input group which is just a little table with some css.
After it is saved I've created another function to build an "event form" for this samples page.
Here's that function:
function new_pt_ss()
{
if ($this->create_npc_SS)
{
$task_id = '13';
if (sql::value("select 1 from event.dbo.event where task_id =" . hexstr($task_id). " and status = 1 and patient_id = " . $this->patient->hex))
return Message::add('New Patient Sample CC already exists. Event not created.', 'warn');
$defs = array('METER KIT', 'TEST STRIP', 'LANCET', 'CONTROL SOLUTION', 'LANCING DEVICE', 'BATTERY', 'MISC');
$task_params = array();
$oks = $this->get_oks();
$oks_hex = array();
foreach ($oks as $k=>$v) $oks_hex[] = hexstr($k);
$qtys = zip($this->items['ptcode'], $this->items['qty']);
foreach ($defs as $x)
{
$me = 0;
foreach ($pt_types as $num=>$row)
{
if ($row['ev_product_type'] == $x)
{
$task_params["{$row['ev_product_type']}"] = $row['ptcode'];
$task_params["{$row['ev_product_type']}_qty"] = $qtys[$row['ptcode']];
if ($x == 'control_solution') $task_params['cs_bill'] = '1';
else if ($x == 'lancing_device') $task_params['lancing_bill'] = '1';
unset($pt_types[$num]);
$me = 1;//continue 2; // preserves sorting instead of continue
}
}
}
$task_params = array_merge($task_params, array('ship_date'=>$this->ship_date
,'urgent'=>$this->urgent
,'valid_po'=>$this->valid_po
,'shipping_method'=>$this->shipping_method
,'reason'=>$this->reason
,'on_insulin'=>$this->on_insulin
,'patient_on_insulin'=>$this->patient_on_insulin
));
Message::check($this->patient->event()->create($task_id, $task_params), "Create Sample CC event.");
return "NEW PT Sample CC EVENT TO BILLING FOR DOS $this->ship_date.";
}
}
After it's submitted if there isn't an event already created for sample ss otherwise known as $task_id = '13'; it will create the event and populate these fields:
,'urgent'=>$this->urgent
,'valid_po'=>$this->valid_po
,'shipping_method'=>$this->shipping_method
,'reason'=>$this->reason
,'on_insulin'=>$this->on_insulin
,'patient_on_insulin'=>$this->patient_on_insulin
The problem is i'm not sure how to populate all the check boxes and select boxes in my for each loop.
These are the field names that need to be populated on the event form:
<tr><td>Meter</td><td><?php sbox('part1',ptdme('E0607'),1, "' onChange=\" reason_swap(this); \" '"); ?></td><input type='hidden' value='1' name='part1_qty'/></tr>
<tr name='inact1' title='56151124' style='display:none;'><td></td>
<td>Send True2Go Meter? <input type='checkbox' name='part8' value='21292002590'/></td><input type='hidden' value='1' name='part8_qty'/></tr>
<tr><td>Strips</td><td><?php sbox('part2', $samp_strips,1,'wide2'); ?></td><td><?php sbox('part2_qty', range(1,10)); ?></td></tr>
<tr><td>Lancets</td><td><?php sbox('part3', $samp_lancets,1,'wide2'); ?></td><td><?php sbox('part3_qty', range(1,10)); ?></td></tr>
<tr><td>Control</td><td><?php sbox('part4', ptdme('A4256'),1,'wide2'); ?></td><input type='hidden' value='1' name='part4_qty'/></tr>
<tr><td>L/D</td><td><?php sbox('part5', ptdme('A4258'),1,'wide2'); ?></td><input type='hidden' value='1' name='part5_qty'/></tr>
<tr><td>Battery</td><td><?php sbox('part6', ptdme('A4235'),1,'wide2'); ?></td><td><?php sbox('part6_qty', range(1,2)); ?></td></tr>
<tr><td>Misc</td><td><?php sbox('part7', ptdme2(array('SAMP','MISC')),1,'wide2'); ?></td><td><?php sbox('part7_qty', range(1,10)); ?></td></tr>
</table>
</fieldset>
I hope that makes sense and i'd be happy to provide more information if needed.
For checkboxes you use checked="checked" or just checked
And for dropdowns you use selected="selected" or just selected
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
Example here
to get a check box or radio button checked you have to set the checked attribute to checked for a combo box you must set the selected attribute to selected on the option element.
I use the following code to complete an ethnicity dropdwon. The code is easy to follow and adaptable. It uses mysql_ which is now deprecated but the principle holds. As you can see, the way to do it is in SQL - you select all your lancets, meterkits, batteries etc SEPARATELY and build each dropdown one at a time. Don't try to sort data in PHP when you can do it in SQL. You're just going to end up writing buggy, difficlut to follow code that is terribly susceptible to minor spelling errors.
I do recommend that you reconsider your user interface. Many diabetic patients are elderly and become easily confused when confronted with dropdowns. They also don't see so well so you may end up with mis-ordering, something select boxes are terribly prone to and for which you are going to get blamed, even if it was the user at fault. Abbreviations like c/s are unwise. Even health professionals are likely to find that UI annoying and may be put off.
$sql="Select ethnicitycode,ethnicitydesc from s_ethnicity where inuse=1 order by ethnicitydesc";
$result=mysql_query($sql,$dbh);
$optext="<select name='ethnicity1' class='select' onChange='Change()'><option value='0'>Choose Ethnicity</option>";
while($row2 = mysql_fetch_array($result))
{
$option=$row2[ethnicitydesc];
$code=$row2[ethnicitycode];
if($row[ethnicitycode1]==$code){$selected="selected='selected'";}else{$selected="";}
$optext=$optext.sprintf("<option value='%s'%s>%s</option>",$code,$selected,$option);
}
$optext=$optext."</select>";
First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.
First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!
If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators
<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...