PHP + MsSQL = Checkbox problems. Need HELP! - php

I have been working on this one topic for weeks. I'm creating a webpage that pulls information from MsSQL server. My problem is where there is a section with few check boxes.
The checkboxes are suppose to be checked if they are found in the SQL database.
If the borrower used money from "Savings", "Checking" and "Stock" those checkboxes should be checked in HTML page. In my case it is only checking whatever is on the first row of the SQL search list. So if the list has "Saving" on the first row, only the "Saving" checkbox will be checked not the rest on the list. I tried using loop (while($r->EOF)), but then it picks whatever is on the end of the list. Here is what I am using to pull data from the SQL server. Thank you in advance for your help. Really appreciate it!
function __construct($_ldid, $_lrid)
$this->ldid = $_ldid;
$this->lrid = $_lrid;
//$loan is defined in the PHP.class (which is shown below).
$q = ("SELECT * FROM Tabel_name where loan_id = 885775")
$v = array($_ldid, $_lrid);
$r = $db->Execute($q, $v);
$this->downpaymenttype = $r->fields; //<- I think I have this line done wrong because it is suppose to store the outputs to an array.
//So wherever the "$loan" is in HTML page, it will take the outputs from the above statement.
//The above code, which is in PHP.class file, outputs the following(or suppose to):
1 885775 Checking
2 885775 Saving
3 885775 Gift
In the HTML webpage, the following codes should check mark the boxes according to the outputs:
<input type="checkbox" name="DPS1[]" id="DPS1-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Checking"} checked {/if}/>
<input type="checkbox" name="DPS2[]" id="DPS2-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Saving"} checked {/if}/>
<input type="checkbox" name="DPS3[]" id="DPS3-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Gift"} checked {/if}/>
Only the "checking" checkbox is getting checked because that's the one on the first row.
I also tried to loop, but it is not storing in array (I guess I don't know how to use the array for session)
$q = ("SELECT Tabel_name FROM loan_downpaymentsource where loan_id = 885775");
$v = array($_ldid, $_lrid));
$r = $db->Execute($q, $v);
while(!$r->EOF) {
$this->downpaymenttype = $r->fields;
$r->MoveNext();
}

Add a loop to go through your results before displaying and set flags. $r->fields is only going to grab the fields for the current row. You need to go through your entire rowset to see if the others are set.
Something like (It looks like you're using adodb or something like that)
$checking = false;
$saving = false;
$gift = false;
while(!$r->EOF){
$row = $r->fields;
switch($row->downpaymenttype){
case 'Checking':
$checking=true;
break;
case 'Saving':
$saving=true;
break;
case 'Gift':
$gift=true;
break;
default:
break;
}
$r->moveNext();
}
Now on your view check the flags. I've not used smarty but you'll have to pass those flags to your template as well as I'm sure you know, and then change your checkbox lines to check if each flag is true/false.
Hope that helps!

Related

Making value checkbox appear

I have a problem with my code. I use CodeIgniter.
I made a checkbox form with a code like this :
foreach ($get_student->result_array() as $row) {
$select_student[$row['student_number']] = $row['student_name'];
echo form_checkbox($select_student,$student_number,FALSE);
}
then the result just like this, only the checkbox appears, the student's name or student number does not appear:
As per the document,
Find the CodeIgnitor form_checkbox documentation
the array should have an element with key='value'.
Hence this line of code
$select_student[$row['student_number']] = $row['student_name'];
should be changed to
$select_student['value'] = $row['student_number'];

How to parse an array into variables (PHP)?

For the life of me I cannot get this to work. I've looked at many articles on stackoverflow so if you could help that would be wonderful! I am working on a form submission for a client. They want to be able to select multiple values from a dropdown, which in turn I will pull from a database to get their query results.
<form id="test" action="results.php" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<?php
$query="SELECT City FROM Cities";
$result = mysqli_query($link, $query);
echo '<select name="city" id="city" multiple>';
while($r = mysqli_fetch_assoc($result)){
echo '<option value="'.$r['City'].'">'.$r['City'].'</option>'; }
?>
</select>
<input type="submit"/>
</form>
//results.php
$results=array();
$results[] = $_POST['role'];
$results[]= $_POST['city'];
echo "<pre>";
print_r($results);
echo "</pre>";
**How do I obtain all the values from the array and parse it into separate variables so I can use the variables in a SQL statement? Here is my output: **
Array
(
[0] => Array
(
[0] => Faculty
[1] => Alumni
)
[2] => Adams
)
Thanks so much for any help! :) And if there is a better way to do this, let me know.
[EDIT] : This code is wild open to SQL Injection , Please don't use it.
One submit options i already have in the question and one i created
dummy submit options for city, run this code in the different file,
than select different different options, and click on submit button,
to check how our query is getting built
Please read the note first and make sure you read the comment in the code, as they are more important than the code
Note 1-> in short you want to run the query, according to the selected options by the user,
make sure you read the comment to understand the logic, comments are more important than the code it's self,
Note 2-> and more thing i did not realize, you may be storing your value in different different table, if that's the case, code will change little bit, but basic shell will remain the same
Note 3-> To achieve the out come which you want to achieve, you basically have to create your query according to the set options, and than use IN keyword and you are good go,
Note 4-> I added echo statement, so you can see stage by stage how our query is developing, i added the comment, if you want see just remove the comment, I did not add the comment in the last echo so you can see the ready to use query string
Note Again-> one submit options i already have, one i created by my self, so you can see what happening, and you it going to work out for you.
as you said in the comment you may have 12 field, in your form, if that's the case, use this code, because lets say if you have to change
some thing in the future, and you have to change at tweleve places,
you will make mistake like miss some thing, or use the wrong variable
or some thing else, with this code, you have to change it one place,
and it will get apply to 12 or 24 places, number of places does not
matter,
and one more thing, it will better if you wrap this php code inside the function, the reason is lets say you have form on some other page, and you need same functionality only thing you have to do than, just call the function, and in the future if you have change some thing, just change the function code
I am giving you example on your code why it is better to wrap this in a function, lets say your table name are different than the given selected name in your form or you decided to hole values in different different table, than you have to change the code, if you wrote this twelve times or each form, and than you have to change it, than you are in big trouble, but if you use this code as function for different different form, you just have to do some changes in function or in here, and will get applied everywhere, in short chances of you screwing up some thing is just not their, so hope fully this will help you
SideNote -- one more thing i want to say, the reason this solution look big, is because of note, form and comment, if you count the php code line, with out the last echo statement, it actually only 10 lines of php code, so dont get afraid, becuase it's look big
<form id="test" action="" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>
<select id="city" name="city[]" multiple>
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="New York">New York</option>
</select>
<input type="submit">
</form>
<?php
//creating variable and saying all the post request is equal to this variable
$selected_options=$_POST;
foreach($selected_options as $key=>$option){
$countValue = count($option);
for($i=0; $i<$countValue; $i++){
/*
* start adding the value seperated by coma, remember again it going to
* be on extra coma so we have to remove it.
*/
$queryString_start_with_coma .= ",$option[$i]";
}
/*
* come out of loop, and now remove that extra coma
*/
$queryString_remove_extra_come= preg_replace("/,/", "", $queryString_start_with_coma, 1);
/*
* start building your query, use variable $key, just check the line below,
* you will understand where and why i am using variable $key.
*/
$query_string_with_and .= " AND $key IN($queryString_remove_extra_come)";
/*
* now unset the variable, this line is very important, so please also check
* your out come without this line,
* what i am simply doing is emptying the variable, if you dont
* do it, it will add the value in the existing value, which i dont want, what
* i want when the loop run for the second selected options, i want my variable
* to be empty, so i can create new string
* you will understand more if you remove this line and compare your two outcome
* Note: you dont have to unset if you dont want to, but you have empty the
* variable, you can also do by creating a empty string, do what ever you want
* to do, just make sure the variable is empty for the second loop
*/
unset($queryString_start);
}
$query_string_second_part_ready = preg_replace("/AND/", "", $query_string_with_and, 1);
//echo "$query_string_second_part_ready<br>";
$query_string= "SELECT * FROM table_name WHERE ".$query_string_second_part_ready;
//see how your query look like
echo $query_string;
It sounds like you want to be able to build a query based on the data submitted by the user. This may be a little more complex if you have multiple tables, but the basic idea is to use the input names with the fields, assemble the query from them, prepare the statement and bind the parameters.
Name the inputs the same as the database fields they match to
// Identify which database fields can be searched
// These names must match the names of the inputs
// Each name has a type which will be used later
$databaseFields = [ 'city' => 's', 'name' => 's', 'grade' => 'i' ];
$databaseFieldNames = array_keys($databaseFields);
// Set up the beginning of the query
$query = 'SELECT * FROM some_table WHERE ';
// Initialize an array to use to store fields to be searched
$where = [];
// Loop through all the post data
foreach ($_POST as $name => $value) {
// If the name is in the database fields list, add it to the query
if (in_array($name,$databaseFieldNames)) {
$where[] = $name;
}
}
// Add all the requested columns to the where
if (!empty($where)) {
$query .= ' '.$where[0].'=?';
array_pop($where);
foreach ($where as $name) {
if (is_array($_POST[$name])) {
// Use any to check for multiple possible values
$query .= ' AND '.$name.' = ANY (?)';
} else {
$query .= ' AND '.$name.'=?';
}
}
} else {
// Avoid an empty WHERE which will cause an error
$query .= ' TRUE';
}
$stmt = mysqli_prepare($query);
/* Bind parameters */
foreach ($where as $name) {
// $_POST should be validated here
if (is_array($_POST[$name])) {
// Arrays are imploded to work in an ANY
$value = "'".implode("','",addslashes($_POST[$name]))."'";
} else {
// Other values are used as sent
$value = $_POST[$name];
}
$type = $databaseFields[$name];
$stmt->bind_param($type,$value);
}
$stmt->execute();

How to insert Multiple records into mysql using php

i am fetching different record from the database but using single quantity field trying to insert multiple records into MYSQL but every time for loop or any other loop overriding single value in all rows(inserting single first value in every field), badly stuck. kindly suggest what kind of appropriate steps should be done.
<input type="text" name="qty[]" id="qtyid" style="width:40px;">
<?php
if(isset($_POST["update"])) {
$usersCount=count($_POST['qty']);
$qtys=implode(",",$_POST['qty']);
for($i=0;$i<$usersCount;$i++) {
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
$total=$total*$qtys;
?>
Your "question" is unclear. I read it couple times nad i still dont know what is your problem.
Anyway. I'll try to explain what your code do in case it would help you to understand where the problem is.
//if form was submited and input of name "update" was in
if(isset($_POST["update"])) {
// count array created by inputs of name="qty[]"
$usersCount=count($_POST['qty']);
// make a string from that array, separating the keys by a "," char
$qtys=implode(",",$_POST['qty']);
// loop as many times as number of elements in that array = <input name="qty[]"> you had in submited form
for($i=0;$i<$usersCount;$i++) {
// and finally, do always the same for each loop repeat
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
So in conclusion your loop is doing always the same - every each repeat:
`$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";`
Basically to do that you would't need to have loop.
Because in that query you change value of column qty wherever column prodid is equal to something

Disable button on conditions

I have a buttons which are displayed from sql query:
$username = new User();
$name = $username->data()->username;
$sql1 = DB::getInstance()->query("SELECT names FROM list WHERE username = '$name'");
if (!$sql1->count()) {
echo 'No data';
} else {
foreach ($sql1->results() as $sql1) {
?>
<p><button class="" > <?php echo $sql1->names; ?></button></p>
<?php
}
}
This displays two buttons which match the conditions from the query, so I'm trying to disable one of the displayed buttons if it doesn't match another condition.
For example, there are two buttons, John and Poodle. And a query to match if one of the buttons is an animal.
So if the button john does not match the query, it should be disabled.
I will try to express the idea sketched in the comments to the question, as you asked me to and explain it step by step:
foreach ($sql1->results() as $set) {
echo sprintf('<p><button %s>%s</button></p>'."\n",
in_array($set->name, array('poodle','cat','sheep')) ? 'disabled' : '',
$set->name);
}
Here $set is a different object (set of attributes) for each iteration of the foreach loop. You said you have two entries in that queries result, so two buttons get generated. Each $set has a name ($set->name) if you understand your code correct (I don't know your database...). This name is used twice for generating each button: first the name is used as text in the button and second it is used in a conditional to decide if the button should be disabled or not. That condition is implemented as a trinary expression, line 3 in the example above. In the line a function is called: in_array(). That returns true or false. If true, then the attribute "disabled" is added to the button, if false then the empty string ('') is added instead, so the button does not have the disabled property.
This is obviously not finished code. It is meant to give you the idea, so you should understand it, not just copy and try it. Feel free to ask if questions arise!
Try the following:
<button class="<?php if($sql1->names != "required_name") echo "disabled" ?>">
<?php echo $sql1->names; ?>
</button>
To disable a button ith php+html, you can try with a query value returned "disabled".
For example: in your query use a CASE WHEN statement to return disabled value when your condition is defined:
SELECT filed1,
CASE
WHEN field1= '19' THEN 'disabled'
WHEN field1='20' THEN ''
WHEN filed1='21' THEN ''
WHEN field1='22' THEN ''
ELSE 'disabled'
END AS for_button
FROM table1 AS tbl1
WHERE tbl1.field1_param = '$param'
Put in the HTML TAG button this:
<input type="submit" value="Button OnOff" <?=$disableButton['for_button']; ?>>
If the value returned is disabled, in the for_button variable, write the valure returned from query and the button will are disabled.

Using For loop to get values of multiple elements in PHP

The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.

Categories