I have a form that generates html checkboxes using php which is shown below
<p><form name="university" action="/university_handler" method="post">
<fieldset>
<table class="table">
<thead>
<tr>
<th><span class="help-block">University Department</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php
$query = mysqli_query($db, "SELECT university_department FROM university WHERE university_id = '$university_id'")
or die ("Could not search!");
while($row = mysqli_fetch_array($query)){
$university_department = $row['university_department'];
$_SESSION['university_department'] = $university_department;
$universityDepartment = $_SESSION['university_department'];
echo "<label><input type='checkbox' name='university_department[]' value='{$universityDepartment}'>$universityDepartment</label><br><input type='text' value='' name='professor_name[{$universityDepartment}]' placeholder='Professor-Name'><input type='text' value='' name='class_name[{$universityDepartment}]' placeholder='Class-Name'>";}
?></td>
</tr>
</tbody>
</table>
<button type="submit" name="Submit"class="btn btn-info">Submit</button>
</fieldset>
</form></p>
Now when I use my university_handler to insert the values into the database all of the check boxes are inserting instead of just the ones that have been checked off. I've been trying a range of things be nothing seems to be working. Here is the handler.
<?php
session_start();
include("connect.php");
$university_id = $_SESSION['university_id'];
// check if share_form is submitted and not empty
$error_message = "";
if(is_array($_POST['university_department']) && !empty($_POST['university_department'])){
$error = array();
$universityDepartment = $_POST['university_department'];
if (count($universityDepartment)>0){
foreach (str_replace('#', '', $_POST['class_name']) as $departmentName => $stripid){
$class_name_backslash = $stripid . '/';
$class_name = mysqli_real_escape_string($db, $stripid);
print_r($class_name);
}
$query_uni = ("INSERT INTO temp_list(departmentName, class_name, professor_name) VALUE ('$departmentName','$class_name', '$professor_name')");
$q_u = mysqli_query($db, $query_uni) or die ('Error posting data');
}
}?>
I like #Martin's answer. The only thing i want to change is the $_REQUEST
When using $_REQUEST you are saying hey look at a post or get variable and use either value. So what happens if you have both a $_POST and a $_GET variable with the same name? One will be used while the other does not.
So lets use the same code in a different way.
$checkBoxName = (isset($_POST['checkBoxName']) ? $_POST['checkBoxName'] : (isset($_GET['checkBoxName']) ? $_GET['checkBoxName'] : ''));
if ($checkBoxName != '') {
//do stuff here
}
This way since you can not see post info without using something like Google Chromes developer tools, its best to do it in this order so you check what is not seen before what you can see.
Hope this helps =)
EDIT:
Based on the information you gave me, i was able to come up with a way to insert only the classes you check off. Feel free to do the change this but this should work
<?php
$departList = ($_POST['university_department'] ? $_POST['university_department'] : ($_GET['university_department'] ? $_GET['university_department'] : array()));
$classList = ($_POST['class_name'] ? $_POST['class_name'] : ($_GET['class_name'] ? $_GET['class_name'] : array()));
$profList = ($_POST['professor_name'] ? $_POST['professor_name'] : ($_GET['professor_name'] ? $_GET['professor_name'] : array()));
if (count($departList) > 0) {
foreach ($departList as $key => $val) {
$class = $classList[$val];
$professor = $profList[$val];
$query_uni = ("INSERT INTO temp_list(departmentName, class_name, professor_name) VALUE ('$val','$class', '$professor')");
$q_u = mysqli_query($db, $query_uni) or die ('Error posting data');
}
}
?>
Good Luck =)
You can use the isset function to check wether the checkbox is checked.
if (isset($_REQUEST['checkBoxName']));
{
$variable = $_REQUEST['checkBoxName'];
}
Using this method you will only get the checkbox that has a value.
Hope this helps
Related
I have a search form where the user will insert his/her CODE and NAME & TELEPHONE of that CODE will then be shown inside a table which is working fine (Thanks to stack overflow).
<form action="list25.php" method="post">
Search By code:<input type="text" name="code"><br><br>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="product-table">
<tr>
<th class="table-header-repeat line-left">Name</th>
<th class="table-header-repeat line-left">telephone</th>
</tr>
<?php
if (isset($_POST['search'])) {
$code = $_POST['code'];
$connect = mysqli_connect("localhost", "root", "", "sahmiye");
$query = "select * from balance where code = $code ";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['telephone']; ?></td>
</tr>
<?php
}
} else {
echo "Undifined ID";
$name = "";
$telephone = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$name = "";
$telephone = "";
}
?>
</table>
<br><br>
<input type="submit" name="search" value="Find">
</form>
BUT i have a second completely different form as well and when the user writes his/her CODE in this second form i needed the NAME & TELEPHONE of that CODE to then be shown inside textboxes and the user will then fill up the rest of the form and then submit it so it can be saved into the database.
The problem being i know i cant have a form within a form but is there a way for me to run my first search form shown above with out using a form so that i can have the same function inside my second form whereby after CODE is given , it will fill up the textboxes with the NAME & TELEPHONE of that CODE ?
Display data from database without using form tags?
You need to use a GET array and use the parameter in the href.
I.e. and checking if it is set and not empty and equal to "something":
Name
Then use the GET array with the parameter.
if(!empty($_GET['var']) && $_GET['var'] == 'John'){
// do your thing to search for the string "John", as an example.
// ATT'N: John and john in the database are two different animals.
}
Use the same format for the other href.
Sidenote: Remove the href's from inside the <form></form> tags, as it may cause some havoc.
You will also need to quote the variable in the query when it is a string.
I.e.:
$query = "select * from balance where code = '$code' ";
...if $code is a string.
However, it will throw an error if the query contains characters that MySQL will complain about such as John's Bar & Grill, therefore a prepared statement/escaping the value will be required and will help prevent a possible SQL injection at the same time.
Reference:
https://en.wikipedia.org/wiki/Prepared_statement
Edit:
Going over the question again and TBH is a bit complicated, using sessions would be something to use in order to keep the values.
http://php.net/manual/en/session.examples.basic.php
...then checking if any of the session array(s) is/are set and not empty.
N.B.: session_start(); must reside inside all pages using sessions in order for this to work. Inputs can also contain sessions-related code and "if set/not empty". Otherwise, you will get errors about them being undefined.
I have a checkbox in a form which I need to disable based on the value in the database. I searched a lot, but can't find any solution that works. Here's the sample code:
<?php
$server_name='localhost';
$username='root';
$password='';
$db_name='checkbox';
$con= mysqli_connect($server_name, $username, $password, $db_name);
if(mysqli_connect_errno())
{
echo 'Failed..!!'.mysqli_connect_errno();
}
$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
$disable = $display?'':'disabled="disabled"';
?>
<html>
<body>
<form name="f1" method="post" action="test2.php">
<input type="checkbox" name="A" value="" <?php echo $disable; ?> />
</form>
</body>
</html>
Thanks in advance.
Far as I can tell, it seems that you may have gotten your ternary's order mixed up.
Now this line is redundant:
$display = (mysqli_num_rows($result) == 1);
You're telling it that it always equals TRUE.
Just set this line to:
$display = mysqli_num_rows($result);
Then the ternary operator will take care of if it's found or not:
$disable = $display ? 'disabled="disabled"': '';
...and if found, disable it.
If that isn't what you're looking to do, then change it back to:
$disable = $display ? '': 'disabled="disabled"';
$result= mysqli_query($con, "SELECT * FROM checkbox WHERE status=1");
$display = (mysqli_num_rows($result) == 1);
Is likely the cause of your problems though it can't be 100% without looking in the database. Does that query return something other than one row? If it does your $display variable will always evaluate to false and not add that disable text to the input field.
Wrap the $disable variable in a var_dump() before you get to the rendering of HTML and see what value you are getting. Or do a direct database query with the one you are triggering off of and see if it is something other than one row.
I tried to create a simple bar chart in D3 taking data from database. The idea is to fetch year and value from the database using the selection buttons of parameters and country and display it in the form of simple bar chart. I have two selection buttons and a submit button. The code for that is like this :
<form action ="data.php" method ="post">
<tr>
<th valign="bottom">Select country:</th>
<td >
<select name="country" class="">
<option value= "NPL">Nepal</option>
<option value= "IND">India</option>
</select>
</td>
<th valign="bottom">Select parameters:</th>
<td >
<select name="indices" class="">
<option value= "foodfinal">Vulnerability on food</option>
<option value= "waterfinal">Vulnerability water </option>
</select>
</td>
<td valign="top">
<input type="submit" class="action" />
</td>
</tr>
</form>
Foodfinal and waterfinal are the names of tables in the database called 'Climate'. NPL and IND are the countrycodes. My PHP code ( data.php ) is like this :
<?php
$username = "root";
$password = "";
$host = "localhost";
$database="climate";
$country="AFG";
$country=$_POST["country"];
$indices=$_POST["indices"];
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `year`, `values` FROM `$indices` WHERE `countrycode`= '$country'";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
?>
My problem is that linegraph.html had been working well before the use of the selection forms but this time, it only displays the output of data.php which looks like this.
{"year":"1995","values":"0.525999"},{"year":"1996","values":"0.570037"},{"year":"1997","values":"0.563966"},{"year":"1998","values":"0.513896"},{"year":"1999","values":"0.5346"},{"year":"2000","values":"0.552691"},{"year":"2001","values":"0.545319"},{"year":"2004","values":"0.543972"},{"year":"2005","values":"0.543299"},{"year":"2006","values":"0.546682"},{"year":"2007","values":"0.550066"},{"year":"2008","values":"0.549449"},{"year":"2009","values":"0.548832"},{"year":"2010","values":"0.548215"},{"year":"2011","values":"0.547536"},{"year":"2012","values":"0.547536"}]
Would you please help me.
change this
include("linegraph.html");
To ( as a best practice thing if the "include" is required to display the page just use require )
require("linegraph.html");
And add at the top of the php
ini_set('display_errors', 1);
You will probably find your page missing ( at the very least your life will be easier with error reporting turned on )
oh and change this part too,
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
To this
$data = array();
while ( false !== ( $row = mysql_fetch_assoc($query))){
$data[] = $row;
}
It probably won't fix your problem ( hard to do without the other html page ) but its the preferred way to do this type of loop.
Update: Here you can't pass both html and json the way you are ( just dawned on me ) you have to pick one. Your problem is a structural one, as you cant do both things at the same time, where does the json data go, it just floats on top of the html? Sorry but it wont work like that, either you already have the html and fill it in with the returned json data, or you build the html with the data already in it and send it back.
change this
echo json_encode($data);
include("linegraph.html");
to ( now you are sending valid json / with the html but you'll have to assemble it client side )
ob_start();
include("linegraph.html");
$html = ob_get_clean();
$responce = array( 'data'=>$data, 'html'=>$html );
echo json_encode($responce);
At the very least your output will change. Hard to say how to do it ( again ) without the other page.
Ok,,,, when I asked to echo something at the bottom did you do this?
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
echo "works";
?> //id remove this end tag it's not needed and can cause problems if there is space ( line returns ) after it. Because it will make you json which you may or may not need invalid.
Oyyy. this is .. uhh
if ( ! $query ) {
echo mysql_error();
die;
}
you can just do like this.
if ( ! $query ) {
die ('Query error' . mysql_error());
}
Im new to php..I had used GridView control in asp.net for Listing records.
Now I want to use a control in php to list the records with checkbox options to select them for deletion and also page enabled. Can anyone guide a beginner on how to do this?
Thanks in advance.
Your idea consists of two things; a table and a php-file that processes the input from the table.
File: table.php
<form method="post" action="process.php">
<table>
<thead>
<tr>
<th>Title</th>
<th>Activate</th>
<th>Delete</th>
</tr>
</thead>
<?php foreach( $records as $record ): ?>
<tr>
<td><?php echo $record['title']; ?></td>
<td><input type="checkbox" name="activate_ids[]" value="<?php echo $record['id']; ?>" /></td>
<td><input type="checkbox" name="delete_ids[]" value="<?php echo $record['id']; ?>" /></td>
</tr>
<?php endforeach; ?>
</table>
</form>
File: process.php
<?php
//Gather the $_POST
$activate_ids = $_POST['activate_ids'];
$delete_ids = $_POST['delete_ids'];
//Let's make sure we only get ints
for($i = 0; $i < count($activate_ids); $i++)$activate_ids[$i] = intval($activated_ids[$i]);
for($i = 0; $i < count($delete_ids); $i++)$delete_ids[$i] = intval($delete_ids[$i]);
//Get the ids
$activate_ids_string = implode(',', $activate_ids);
$delete_ids_string = implode(',', $delete_ids);
//Make sure we don't have '' as a parameter for SQL
if( $activate_ids_string == '' ) $activate_ids_string = 0
if( $delete_ids_string == '' ) $delete_ids_string = 0;
//UPDATE the table
$sql_activate = 'UPDATE Records SET active=1 WHERE id IN (' . $activate_ids_string . ')';
$sql_delete = 'DELETE FROM Records WHERE id IN (' . $delete_ids_string . ')';
//Execute the queries and get the # of affected rows
$aff_rows_activate = mysql_num_rows(mysql_query($sql_activate));
$aff_rows_delete = mysql_num_rows(mysql_query($sql_delete));
//Last but not least, output how it went for both queries
if( $aff_rows_activate === 1 ) echo 'Activated one record.';
else echo 'Activated ' , $aff_rows_activate, ' records.';
if( $aff_rows_delete === 1 ) echo 'Deleted one record.';
else echo 'Deleted ' , $aff_rows_activate, ' records.';
?>
I haven't had a chance to try out the code above, so there might still be a couple of syntax errors in it - however, you should be able to get an idea of what you need to do to achieve the results that you want.
php is different form asp. asp has many controls whcih u can use but php has core function for core funtionlity. to achive ur goal u have to use table put checkbox in the table with ur data in it and use ajax to delete rows from the table or just post the page on checkbox click. but there is no control for this u have to code it urself, u can say php is like c++. and for paging u can use some class which are find here enter link description here
I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.