two dropdown menu and one button - php

I want to ask about this code. I have two dropdown menu and one button. I want to search in sql database what I choose in those drop down menu. What is the sql syntax for search item in sql database by using two drop down menu.
my database = test
Table = student
name | class | sex | mark |
John | Five | Male | 75
Jashi | Four | Female | 89 |
##HTML##
<form action="search2.php" method="post">
<select name="class">
<option value="" selected="selected">Class</option>
</select>
<select name="sex">
<option value="" selected="selected">Sex</option>
</select>
<input type="submit" value="search" />
</form>
search2.php
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
$whereClauses = '';
$class = count($_POST['class']);
$sex = count($_POST['sex']);
$i = 0;
if (! empty($_POST['class'])) {
foreach ($_POST['class'] as $class) {
$whereClauses .="class='".mysql_real_escape_string($class)."'";
if ($i++ == $class) {
$whereClauses .= " AND";
}
}
}
if (! empty($_POST['sex'])) {
foreach ($_POST['sex'] as $sex) {
$whereClauses .="sex='".mysql_real_escape_string($sex)."'";
}
if ($i++ == $sex) {
$whereClauses .= " AND";
}
}
$sql = "SELECT * FROM student '".$where."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['class'];
echo $row['sex'];
echo $row['mark'];
}
?>
ANY HELP WOULD BE APPRECIATED

If I got it right and you want to search for students by class and sex (gender?) you can use this SQL query:
SELECT * FROM `student` WHERE `class` = 'the_class' AND `sex` = 'the_sex';
Where:
the_class is the input from your choose Class dropdown
the_sex is the input from your choose Sex dropdown

If I understand it correctly, you want the input of two drop down menu's to define the Mysql query? In that case, you can simply first check whether the user has selected two values, and then you could change your query accordingly by adding the "AND" to the Mysql Query.
For example:
if(isset($_GET["class"]) && isset($_GET["sex"])) {
$result = mysql_query("SELECT * from student Where sex = '". $_GET["sex"]."' AND class = '".$_GET["class"]."'");
}
Of course, in the above mentioned solution I presume that you are aware how to POST and GET data through html forms and PHP.

Related

Convert select into mysql php input

I have an order form where the product is selected from a database with the method "select" and "option". I show screenshot and code
Code:
<div class="form-group">
<select class="form-control" name="productName[]" id="productName<?php echo $x; ?>" onchange="getProductData(<?php echo $x; ?>)" >
<option value="">-- Selecciona --</option>
<?php
$productSql = "SELECT * FROM product WHERE active = 1 AND status = 1 AND
quantity != 0";
$productData = $connect->query($productSql);
while($row = $productData->fetch_array()) {
$selected = "";
if($row['product_id'] == $orderItemData['product_id']) {
$selected = "selected";
} else {
$selected = "";
}
echo "<option value='".$row['product_id']."'
id='changeProduct".$row['product_id']."' ".$selected."
>".$row['product_name']."</option>";
} // /while
?>
</select>
</div>
I would like to transform this way of selecting a product (droping-down list using "select") for an order form in a field that can be input the first letters of the name of the product or reference and I can see in the drop-down list those references that match instead of all references in table. I know that "input" and "post" should be used and in the query to the database something like:
// Conexión a la base de datos y seleccion de registros
$con=mysql_connect("localhost","xxxxx_xxxx","xxxxxxx");
$sql = "SELECT * FROM product WHERE referencia, product_name, position_store
like ‘%$buscar%’ ORDER BY id DESC";
mysql_select_db("xxxxxxx_stock", $con);
$result = mysql_query($sql, $con);
The idea is to do what I show in the screenshot:
Once the matches appear, you can select the one that interests you. I'm not sure how to structure the changes to convert the initial code into what I'm looking for.
I appreciate any help.

Sending Multiple Select to MySQL in PHP

I am trying to upload two sets of multiple selects into a MariaDB database (many to many relationship intermediate table). The selected options are being properly uploaded but the code is also sending in the last entry from both selects. In other words, if I select options 1 and 4 from the first select that contains 10 options, and I select 5 and 12 from the second select that contains 15 options, instead of populating 4 entries (1 and 5, 1 and 12, 4 and 5, 4 and 12) it is populating 9 options (the four that are supposed to be there plus 1 and 15, 4 and 15, 10 and 15, etc). Each select is populated from the two tables. Below is the code.
<?php
include ("connect_movieDB.php");
connectDB();
$display_block = "<h1>Populate Movie-Actor table</h1></br>
<p>Select a movie and select the actors</p>";
$get_movie_sql = "SELECT id as movie_id, movie_title, movie_releasedate FROM movies ORDER BY movie_title asc";
$get_movie_results = mysqli_query($mysqli, $get_movie_sql) or die(mysqli_error($mysqli));
$get_actor_sql = "SELECT id as actor_id, CONCAT_WS(' ', f_name, l_name) AS display_name FROM actors ORDER BY l_name asc, f_name asc";
$get_actor_results = mysqli_query($mysqli, $get_actor_sql) or die(mysqli_error($mysqli));
if ((mysqli_num_rows($get_movie_results) < 1) || (mysqli_num_rows($get_actor_results) < 1)) {
$display_block .= "<p><em>Did we forget to populate the database?</em></p>";
} else {
$display_block .= "
<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">
<p><label for=\"sel_movie\">Select a movie:</label></br>
<select id=\"sel_movie\" size=\"10\" name=\"sel_movie[]\" required=\"required\" multiple=\"multiple\">
<option value=\"\">--Select a Movie--</option>";
while ($movies = mysqli_fetch_array($get_movie_results)) {
$movieid = $movies['movie_id'];
$display_movie_title = stripslashes($movies['movie_title']);
$display_moviedate = stripslashes($movies['movie_releasedate']);
$display_block .="<option value=\"".$movieid."\">".$display_movie_title." - (".$display_moviedate.")</option>";
}
$display_block .= "
</select></br>
<p><label for \"sel_actor\">Select the actors in the movie:</label></br>
<select id=\"sel_actor\" size=\"10\" name=\"sel_actor[]\" required=\"required\" multiple=\"multiple\">
<option value=\"\">--Select actor(s)--</option>";
while ($actors = mysqli_fetch_array($get_actor_results)) {
$actorid = $actors['actor_id'];
$display_actor_name = stripslashes($actors['display_name']);
$display_block .="<option value=\"".$actorid."\">".$display_actor_name."</option>";
}
$display_block .="
</select></p>
<input type=\"hidden\" name=\"sel_movie[]\" value='".$movieid."'/>
<input type=\"hidden\" name=\"sel_actor[]\" value='".$actorid."'/>
<button = type=\"submit\" name=\"submit\" value=\"addtotable\">Add Relationship</button>
<p>Return to the main menu</p>
</form>";
}
if ($_POST) {
if ((isset($_POST['sel_movie'])=="") || (isset($_POST['sel_actor'])=="")){
header("location: addto_ma_table.php");
exit;
}
connectDB();
$movie_array = $_POST['sel_movie'];
$actor_array = $_POST['sel_actor'];
foreach($movie_array as $m) {
foreach($actor_array as $a) {
$check_sql = "SELECT movie_id, actor_id FROM movie_actor WHERE movie_id ='".$m."' AND actor_id ='".$a."'";
$check_results = mysqli_query($mysqli, $check_sql) or die(mysqli_error($mysqli));
$add_info_sql = "INSERT INTO movie_actor (movie_id, actor_id) VALUES ('".$m."', '".$a."')";
$add_info_results = mysqli_query($mysqli, $add_info_sql) or die(mysqli_error($mysqli));
header("Location: addto_ma_table.php");
}
} mysqli_close($mysqli);
}
?>
Thanks for any assistance
There are two hidden inputs after you close the second select. They are adding the last values from your queries to the post arrays. Remove those and it should work better.

How do I insert multiple records into a mysql database, using a combination of checkboxes and html select

Suppose someone selects 2 students along with 1 teacher
How do I send/create 2 different records in MYSQL database,
- one NEW Record for each student/teacher combo
HTML:
1.) Here I can Select as many as "FOUR" students:
<input type="checkbox" name="ALM[]" value="Bob" >Bob<br />
<input type="checkbox" name="ALM[]" value="Stacy" >Stacy<br />
<input type="checkbox" name="ALM[]" value="John" >John<br />
<input type="checkbox" name="ALM[]" value="Liam" >Liam<br />
2.) Here below I am Selecting "ONE" Teacher:
<select name="TCH">
<option value="Dan">Dan</option>
<option vaule="Rick">Rick</option>
If I select Bob and Stacy (students) and Rick (teacher) I need.
2 records 1.) Bob | Rick. 2.) Stacy | Rick.
PHP:
This is my PHP where I Separate the incoming Checkbox Data and try to send to Database
$ALM = implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$query = "INSERT INTO cl_st_tch (students_id,teachers_id)
VALUES"; for ($i=0; $i<sizeof($ALM); $i++)
$query .= "('" . $ALM[$i] . "','$TCH'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );
What am I missing? Any Help would be greatly appreciated
To avoid multiple SQL queries a single query can be built.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$arr = array();
$query = 'INSERT INTO cl_st_tch (students_id,teachers_id) VALUES ';
foreach($ALM as $student){
$arr[] = '('.$student.','.$TCH.')';
}
if(!empty($arr)) {
$query .= implode(', ', $arr);
mysql_query($query);
}
?>
Since your ratio is 1:n (1 teacher to many students),
Iterate through each of the students and add a teacher to each one.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
foreach($ALM as $student){
$query = "INSERT INTO cl_st_tch (students_id,teachers_id) VALUES($student, $TCH)";
mysql_query($query);
}
?>

Insert selected radio values into a specific id of the table- php mysql

I have a table in database, and when want to reject or accept someone's application i just select the radio button and send the value to the table in database.
But the problem is that the value is assigned to new row and not to the specific student id. Here is my table as you see there are added 2 new rows getting another id. Here is my code and table:
<?php
$status = $_POST["status"];
$connect = mysqli_connect("localhost","root","admin","form");
if (!$connect) {
die('Connect error:'. mysqli_error());
}
$result = mysqli_query($connect, "INSERT INTO students (status) VALUES ('$status') ");
?>
idstudents |fname | lname| age | nationality | status
.....................................................
1 |Tom | Bern | 23 | American |
2 |Lily | Wayne| 24 | British |
3 |NULL | NULL | NULL| NULL | accepted
In order to update, you need an UPDATE statment, dont forget to add a student_id on the form. Consider this example: (Same Page Process).
<?php
$students = array();
$link = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_POST['submit'], $_POST['status'])) {
$status = $_POST['status'];
foreach($status as $student_id => $status_value) {
$stmt = $link->prepare('UPDATE students SET status = ? WHERE idstudents = ?');
$stmt->bind_param('ss', $status_value, $student_id);
$stmt->execute();
}
}
$query = mysqli_query($link, 'SELECT * FROM students');
while($row = $query->fetch_assoc()) {
$students[] = $row;
}
?>
<form method="POST" action="">
<?php foreach($students as $key => $value): ?>
<fieldset>
<p>
Name: <?php echo $value['fname'] . " " . $value['lname']; ?><br/>
Status: <b><?php echo ($value['status'] != '') ? $value['status'] : 'N/A'; ?></b><br/>
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="accepted" /> Accepted
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="rejected" /> Rejected
</p>
</fieldset>
<?php endforeach; ?>
<input type="submit" name="submit" value="Update" />
</form>
Note: Since you are using mysqli now, take advantage of parameterized queries. Dont directly use your $_POST values on the query.
The INSERT statement is meant to... Insert a new row. What you need is an UPDATE statement, to apply a value to a certain row, which you are going to select using their idstudents.
$status = $_POST["status"];
$studentid = $_POST["studentid"];
...
$result = mysqli_query($connect, "UPDATE students SET status = '$status' WHERE idstudents = $studentid;");
On a side note, always be careful when using $_POST (or other) values entered by the user, if this service is going to be used by other people, you might want to sanitize them before inserting them, to avoid potential security breaches.

Delete row when checkbox previously selected is deselected

I have a table naming related_products,
Where
products_id is the main product.
and related_products_ids consist of product ids related to the main product.
--------------------------------------------
| products_id | related_products_ids |
| -----------------------------------------
| 1 | 2 |
| -----------------------------------------
| 1 | 4 |
| -----------------------------------------
| 1 | 3 |
-------------------------------------------
I have checkboxes,
<input value="2" type="checkbox" name="rp_product[]" id="in-category2"> Microsoft IntelliMouse Pro 2
<input value="3" type="checkbox" name="rp_product[]" id="in-category3"> Microsoft IntelliMouse Pro 3
<input value="4" type="checkbox" name="rp_product[]" id="in-category3"> Microsoft IntelliMouse Pro 4
The checkboxes are generated by php,
<?php
echo '<ul id="categorychecklist" class="list:category categorychecklist form-no-clear">';
global $wpdb;
$sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$HTTP_GET_VARS['pID']."'";
$result = mysql_query($sql);
$rps = array();
while($row = mysql_fetch_assoc($result)) {
$rps[]=$row["related_products_ids"];
}
$rp_sql = "select products_id, products_name from ".TABLE_PRODUCTS_DESCRIPTION." where products_id !='" . (int)$HTTP_GET_VARS['pID']."' order by products_name";
$rp_1 = mysql_query($rp_sql);
while($rp_2 = mysql_fetch_array($rp_1)) {
$checked = '';
if (in_array($rp_2['products_id'], $rps)) $checked = " checked";
echo "<li id=\"category-".$rp_2['products_id']."\" class=\"popular-category\"><label class=\"selectit\"><input value=\"".$rp_2['products_id']."\" type=\"checkbox\" name=\"rp_product[]\" class=\"rp_item\"" . $checked . "> <span>".$rp_2['products_name']."</span></label></li>";
}
mysql_free_result($rp_1);
echo '</ul></div></div>';
?>
And i use this code to save the checked checkboxes to the related_products table,
for ($i=0; $i<count($_POST['rp_product']); $i++)
{
$check_val1 .= $_POST['rp_product'][$i] .","; //gather data
}
$check_val = trim($check_val1, ','); //clean last ,
unset($check_val1); //flush
$insert_rp_ids1 = explode(',', $check_val);
foreach($insert_rp_ids1 as $id){
$rps_each2 = array('products_id' => $products_id, 'related_products_ids' => $id);
$wpdb->insert(TABLE_RELATED_PRODUCTS, $rps_each2);
}
What i want is to delete a particular id under related_products_ids column when the checkbox previously selected is deselected..
Lets say im editing the post where the products_id is 1 and where the related_products_ids of it is 2, 3 and 4.. I deselected the checkbox where the value is 3(which is on the related_products_ids) and after hitting the save button, the value 3 on the related_products_ids will be deleted so that current rows now is 2 and 4. How to do that? I can't think and find a solution for this.
Please help.
<script type="text/javascript">
var home = "http://www.mysite.com/";
function performAction(url) {
document.getElementById("actionFrame").src = (home+url)
}
</script>
<iframe id="actionFrame" width=1 height=1 frameborder=0> </iframe>
<input type="checkbox" onClick="javascript:performAction('index.php?check=1&action=del');" /> Delete row
<input type="checkbox" onClick="javascript:performAction('index.php?check=2&action=del');" /> Delete row
All of the variables should be written in PHP when the page is written e.g.:
for ($i=0; $i<sizeof($some_array); $i++) {
$input = "<input type=\"checkbox\""
. "onClick=\"javascript:performAction('index.php?check=".($i+1)."&action=del');\" />";
echo $input;
}
The PHP page will have something like this to perform the delete:
$action = $_GET["action"];
$check = $_GET["check"];
switch ($action) {
case "del":
delRow($check);
break;
}
require_once("database.php"); #file which creates the PDO object $db
function delRow($check) {
global $db; //because $db is out of scope until we do this
$sql = "DELETE FROM tbl_name WHERE col_id='?';";
$query = $db->prepare($sql);
$query->bindParam((int)$check);
$query->execute();
$rows = $query->rowCount();
echo "$rows were deleted.";
}
The logic here is that on edit action all related products are repopulated in database. If they are repopulated, then the easiest is to remove them before.
To achieve this, on submit, just before you insert anything to related_products table, delete all rows where products_id equals $products_id. Do this between the two lines in your code:
$insert_rp_ids1 = explode(',', $check_val);
and
foreach($insert_rp_ids1 as $id){
In addition, you may consider using transaction or, if not supported by your table, checking if the delete statement succeeded.

Categories