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 >
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" >
<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 ?
CodePudding user response:
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 >
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" >
<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;
}
?>
CodePudding user response:
The easiest way is to use onclick=
and then the name_of_function ();
for example:
<div >
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" >
<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.
CodePudding user response:
I just coded this for you :) full working, you can make it better. Just add onchange='this.form.submit();'
<form id="companyForm" name="companyForm" type=get>
<div >
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" onchange='this.form.submit();' >
<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);
?>
CodePudding user response:
This is riskier - the application is vulnerable to SQL injection or plain SQL attack.
Are you using any ORM for php-framework, or else you can use stored_procedure
.