Run an SQL Script from a drop down menu - php

I'm trying to create a drop down menu and run specific SQL scripts depending to each option value.
Part of the php code is this (I've made labels more easy for you to understand what i want):
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
</div>
Lets say the RunScript1 is supposed to run the SQL command
truncate table table_name1. How can i do that from inside php menu ?

The easiest way is to use onclick= and then the name_of_function ();
for example:
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option onclick="RunScript1()">Delete Whole Table</option>
<option onclick="RunScript2()">Run Script 3</option>
</select>
</div>
And then according to the function's name.
Create the appropriate functions to run on click.

You can submit the form to the server and execute the request you need.
<?php
$db = new mysqli('localhost', 'db_user', '1234', 'db_name');
if($db->connect_errno)die('Error: '.$db->connect_error);
?>
<form name="runSQL" method="get">
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
<input type="submit" value="Run">
</div>
</form>
<?php
$runSQL = $_GET['RunningSQLScripts'];
switch($runSQL){
case 'RunScript1':
$db->query("truncate table `name`");
echo '* Successfully deleted *';
break;
case 'RunScript2':
$db->query("SQL");
echo '* Successfully run *';
break;
}
?>

Easiest way to do it: fully working,
Just add
onchange='this.form.submit();'
<form id="companyForm" name="companyForm" class="form-horizontal" type=get>
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" onchange='this.form.submit();' class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
</div>
</form>
<?php
$RunningSQLScripts = $_GET['RunningSQLScripts'];
$con = mysqli_connect('host','username','password','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
if ($RunningSQLScripts == "RunScript1")
{
$sql="truncate TABLE `table_name1`;"; // truncate table table_name1
$result = mysqli_query($con,$sql);
}
mysqli_close($con);
?>

Related

How can I pass an HTML value to a PHP variable

I have a simple web app made with CodeIgniter 3 and I have created a simple dropdown menu where the user can select from a variety of options from the database.
Here is the code:
<?php
$sql4 = "SELECT DISTINCT (color), id FROM porta_color ORDER BY color ASC ";
$result4 = $conn->query($sql4);
?>
<select id="color" class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="k_color" required >
<?php
if ($result4->num_rows > 0)
{
while($row4 = $result4->fetch_assoc())
{
if($row4['id']>0)
{?>
<option value="<?=$row4['id'];?>"><?=$row4['color'];?></option>
<?php }}}?>
</select>
Now what I want to do is based on the selection from the user to pass the value to a PHP variable.
Any idea how I might do that?
Wrap your select into form tags
and add submit or button element
<form>
<select id="color" class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="k_color" required >
<option value="color1">Color 1</option>
<option value="color2">Color 2</option>
<option value="color3">Color 3</option>
</select>
<input type="submit" values="Choose color">
<button>Another way for submit form</button>
</form>
But true way is using framework abilities

Can't get data from Dropdown List PHP to Xampp MySQL

I'm trying to get that from a dropdown list from my html.
<FORM ID="" ACTION="save.php">
<TABLE BORDER=1 WIDTH=90%>
<TR>
<TH><p style="color:red">Time</p></TH>
</TR>
<TR>
<TD>
<SELECT NAME="Time" ID="Time" style="width:220px">
<OPTION>
<OPTION>7:30-8:30
<OPTION>7:30-9:00
<OPTION>7:30-10:30
</SELECT>
</TD>
What happens is when the user click the submit button, it automatically call save.php
<?php
$time = $_POST['Time'];
//create connection_aborted
$conn = mysqli_connect("localhost", "root", "", "scheduling");
//check connection
if($conn-> connect_error) {
die ("connection failed; ". $conn-> connect_error);
}
$sql = "INSERT INTO sched (Time)VALUES ('$time')";
$conn->close();
?>
This technique works on textbox, I don't know why can't get data from drop down list. Am I missing something? Please help to fix.
You need set the option value like this:
<select id="Time" required>
<option value="">Please Select</option>
<option value="7:30-8:30">7:30-8:30</option>
<option value="7:30-9:00">7:30-9:00</option>
<option value="7:30-10:30">7:30-10:30</option>
</select>
And if you have option with blank value, good to check in php first before insert like this
if (!empty($_POST['Time'])) $Time = $_POST['Time'];
Your option tags need a value attribute to send to the server. Try this:
<SELECT NAME="Time" ID="Time" style="width:220px">
<OPTION value=""></OPTION>
<OPTION value="7:30-8:30">7:30-8:30</OPTION>
<OPTION value="7:30-9:00">7:30-9:00</OPTION>
<OPTION value="7:30-10:30">7:30-10:30</OPTION>
</SELECT>
<select id="Time" name="Time">
<option disabled="disabled" selected="selected" value="">Please Select One</option>
<option value="7:30-8:30">7:30-8:30</option>
<option value="7:30-9:00">7:30-9:00</option>
<option value="7:30-10:30">7:30-10:30</option>
</select>

How do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

Whats the possibility of one updating a database field with a form having a drop down without changing the value of the drop down field

Lets say i input data into a mysql database using a drop down like:
<div>
<input name="name" type="text" id="name" placeholder="Enter Name"></div>
<div>
<select name="position" id="position" type="text">
<option selected="selected">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
With a normal text field, i can simply include the value field to show on the form the initially entered data in the table. And change that so when i submit form, it updates the related field.
<div>
<select name="position" id="position" type="text" value="<?php echo $row_position['Position']; ?>>
<option selected="selected">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
So assuming i do not want to update the field relating to the drop down, how do i it? Because what happens is, once i submit the form without selecting any option from the drop down, it picks the first option from the list which is the "Select" option and uses that to update the related field in the database.
I'd suggest at least two steps to make it user-friendly and achieve your goals:
First, make the initially entered selection selected if available:
<?php
$positions = Array("A", "B", "C");
?>
<div>
<select name="position" id="position">
<option value="-1">Select</option>
<?php
foreach($positions as $v) {
$selected = ($row_position['Position']===$v) ? "selected" : "";
echo "<option value='$v' $selected>$v</option>";
}
?>
</select>
</div>
And on the receiving php-script check if you've received a valid option, otherwise send error-message:
<?php
//other stuff...
if($_POST['position']>0) {
// save that value
} else {
// send error to user
}
// even more stuff..
?>
Notes: in select tag there is no type=text nor a value=anything available.
Assuming you are fetching dropdown options from database.
Note: Array keys, variables are only for demonstration purposes. This may differ from your actual records.
<div>
<select name="position" id="position">
<?php foreach($options as $option): ?>
<option value="<?= $option['position'] ?>" <?php if($option['position'] == $current_record['position']) { echo "selected"; } ?>> <!-- e.g. $option['id'] -->
<?= $option['name'] ?>
</option>
<? endforeach; ?>
</select>
</div>
What i have done that has solved the issue was to simply add the value from the database to the selectedoption or the first option field. So by default without changing the drop down, the first option with the value from the database is selected. And so there would be no change.
<div>
<div><?php echo $row_position['Position']; ?></div>
<select name="position" id="position">
<option value="<?php echo $row_position['Position']; ?>Select to Change</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
This gives a simple or straight forward solution to the problem.
Will still try the other suggestions to see how it all plays out. Thanks guys.

dynamic dropdown list-get values from mysql

i have this code.it is a dropdown list and a submit button.
I have a query "SELECT * DISTINCT column_name FROM table_name" that has result 15 values
Now,i want to take those values of the query and dynamicly enter them on the option=..... field.Also the "NAME" section must be the same as values.
example: IF value1="abcd"
<option value="abcd" >abcd</option>
<!DOCTYPE html>
<html>
<body>
<form method="post" target=".....php">
<select name="exa" >
<option value="value1" >NAME 1</option>
<option value="value2" >NAME 2</option>
<option value="value3" >NAME 3</option>
<option value="value4" >NAME 4</option>
<option value="value5" >NAME 5</option>
<option value="value6" >NAME 6</option>
<option value="value7" >NAME 7</option>
<option value="value8" >NAME 8</option>
<option value="value9" > NAME 9</option>
<option value="value10" >NAME 10</option>
<option value="value11" >NAME 11</option>
<option value="value12" >NAME 12</option>
<option value="value13" >NAME 13</option>
<option value="value14" >NAME 14</option>
<option value="value15" >NAME 15</option>
</select>
<form action=$value>
<input type="submit" value="GO!" />
</form>
</body>
</html>
i've made this but didnt work
<!DOCTYPE html>
<html>
<body>
<form method="post" >
<select name="exa" >
<?php
include_once "LOGIN TO DB SCRIPT";
$query_ak='SELECT DISTINCT (column_name) FROM table_name';
$result = mysql_query ($query_ak) or die (mysql_error);
while ($row = mysql_fetch_assoc($result)) {
}
?>
<option value = $row['ak_ex']> "$row['ak_ex']"</option>
<input type="submit" value="GO!" name="go"/>
</select>
</form>
</body>
</html>
You have made a lot of errors, first you've put the OPTION object outside the WHILE loop, then you put the submit button inside the SELECT object, in the end you write distinct as a function, the correct syntax is below.
I suggest you to use mysqli to avoid security problem and because mysql is going to be DEPRECATED. Use also include and not include_once because it requires extra work from PHP to render the file(Little difference but everything is welcome).
I've modified the code to use it, you find all the information to modify your script for working with mysqli at http://php.net/manual/it/book.mysqli.php
<html>
<body>
<form method="post" >
<?php
// LOGIN TO DATABASE SCRIPT WRITTEN FOR MYSQLI
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// END OF LOGIN TO DB SCRIPT
include DATABASE CONFIGURATION;
$query_ak='SELECT DISTINCT column_name FROM table_name';
$result = $mysqli->query($query_ak);
?>
<select name="exa" >
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['ak_ex'].'">'.$row['ak_ex'].'</option>';
}
?>
</select>
<input type="submit" value="GO!" name="go"/>
</form>
</body>
</html>
You should placed <option>...</option> inside loop. Place submit button outside </select> tag. You also have syntax error. mysql_error should be mysql_error().
<!DOCTYPE html>
<html>
<body>
<form method="post" >
<?php
include_once "LOGIN TO DB SCRIPT";
$query_ak='SELECT DISTINCT (column_name) FROM table_name';
$result = mysql_query ($query_ak) or die (mysql_error());
?>
<select name="exa" >
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['ak_ex'].'">'.$row['ak_ex'].'</option>';
}
?>
</select>
<input type="submit" value="GO!" name="go"/>
</form>
</body>
</html>

Categories