Retrieving query results from inside radio buttons - php

I am trying to echo out or print out the query results from this radio button:
<input type="radio" name="Query" value="SELECT employees.name FROM employees, department WHERE employees.department_deptID=department.deptID AND department.departName="Information Technology""> List all employees in a particular department (Information Technology).<br />
The code I currently am using is this:
if ($_POST['submit'] == "submit" && isset($_POST['Query'])){
$query = $_POST['Query'];
$result = mysql_query($query);
print $query;
while($row = mysql_fetch_assoc($result)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
}
Along with a few other radio buttons I also have a submit button to initiate the action:
<input type="submit" name="submit" value="submit">
Thanks in advance for any help.

Try the following block:
<input type="radio" name="Query" value="SELECT employees.name FROM employees, department WHERE employees.department_deptID=department.deptID AND department.departName='Information Technology'"> List all employees in a particular department (Information Technology).<br />
I have replaced the " with ' at department.departName='Information Technology'
Note: This whole logic looks bad idea to me. You are passing the query from the browser which results in high risk. Also use mysqli_* functions and stop using mysql_* functions

Related

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth

How to show results of a form upon submission

Using WordPress, so PHP, HTML, CSS, JavaScript what is the best method of populating the results of a form upon submission? I could have a form with ddl, radio buttons, etc.
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
What is the best way of populating the results i.e. "67% of users are Female" and "30% ride bikes" on the same page once the submit button is triggered?
Try something along these lines:
script.php
----------
<html>
<body>
<form method=post action=script.php>
your form here...
</form>
<? if($_SERVER["CONTENT_LENGTH"]>0) {
//form was submitted to script, so process form inputs here and display results...
}
?>
</body>
</html>
<form action="phpfile.php" method="Post">
...form here
</form>
phpfile.php:
<?php
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}//etc..
//To show the result, simply echo it:
echo $sex;
You'll need some sort of storage system to be able to calculate the amount of each.
So what you would need to do is write a simple query where the value of the field is male or female. Then you can easily calculate it.
What you will need to do is add the form results to the database, then find the total number of results for both categories, then calculate the percent female and the percent bike.
The form page:
<html>
<?php
if(isset($_GET['status']) && $_GET['status'] == "values") {
//connect to DB and select table
$male = count( mysql_query("SELECT gender FROM Table WHERE gender='male'"));
$female = count (mysql_query("SELECT gender FROM Table WHERE gender='female'"));
$car = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='car'"));
$bike = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='bike'"));
$totalResults = $male + $female;
$totalVehicles = $car + $bike;
$percentFemale = 100 * ($female / $totalResults);
$percentFemale = number_format($percentFemale, 0);
$percentBike = 100 * ($bike / $totalVehicals);
$percentBike = number_format($totalBike, 0);
echo "<p>" . $percentFemale . "% of users are female. </p>";
echo "<p>" . $percentBike . "% of users use bikes. </p>";
} else { ?>
<form action="formProcessor.php" method="POST"><!-- You could also use GET -->
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
<?php } ?>
</html>
The formProcessor.php Page:
<?php
if(isset($_POST["sex"]) && isset($_POST['vehicle'])) {
//Connect to MySQL DB and select table here
$sex = $_POST['sex'];
$vehicle = $_POST['vehicle'];
mysql_query("INSERT INTO Table(sex, vehicle) VALUES($sex, $vehicle)"); //You may also want to add an id column, but...
//Close mysql connection
header("Location: /form.php?status=values");
die();
} else {
die("There was an error in your submission.");
}
?>
I think this answers your question, you've got a way to find the percent of female users and users on bikes. If you need that to be dynamic and show only the greater amount (or show both or something) just add a comment. This also assumes you are not using PDO, if you are, I can adjust the code. I just wrote the code, so I don't know for sure if it works, but here you go!

get selected value of a drop down which is populated with results from an SQL query

So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:
<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
<input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
<select name="Name_dropdown" id="name_dropdown" style="width: 200px" >
<?php
$ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";
$ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());
while ($row= mysql_fetch_array($ClientName_Result)){
echo "<option> $row[FullName] </option>";
}
?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>
In your ClientDetails.php file the value will be available using,
$name = $_POST['Name_dropdown'];
If you need to change a setting in the form document before submitting you can use jQuery. Something like
$('#name_dropdown').change(function(){
var option = $(this.options[this.selectedIndex]).val();
});

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

display data from database after chekcbox selection

I want to have a form that allows the user to choose what data to display from a table through checking the checkboxes. If the user wants only 2 columns to be shown, should only 2 columns be shown. I have my codes, but after I submit, it displays nothing.Here's my code:
<form name="form1" method="post" action="view_emp.php">
<p>Select Option
<input type="checkbox" name="number[]" value="name" />Name
<input type="checkbox" name="number[]" value="hired" />Date Hired
<input type="checkbox" name="number[]" value="basic" />Basic Pay
<input type="checkbox" name="number[]" value="incentives">Incentives
</p>
<input type="submit" name="Submit" value="Submit">
</form>
here's my php:
<?php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('eis', $db) or die (mysql_error());
$employee = array();
foreach ($_POST['number'] as $employee) {
$number = mysql_real_escape_string($number);
$employee[] = "'{$number}'";
}
$sql = "select * from employees where type in (" .implode(", ", $number). ")";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
print $row['name'];
}
?>
i am a beginner in php and i need help from gurus and experts. thank you...
PHP's implode() and explode() functions might come in handy. You can easily turn your POST or GET attribute, 'number', into a comma-separated list by using implode($_POST['number']). This would be easy to store in one MySQL field, maybe a column in your user table.
If you want users to edit the form later, render the checkboxes with a loop and add a "checked" attribute to each checkbox element whose name exists in 'exploded' list (array) retrieved from your database.
This is basically serialization/deserialization. There are other ways to do it including serialize(), unserialize() or json_encode(), json_decode(). But since your data seems to be easily modeled as a basic list, you can keep it even simpler.

Categories