Calling mysql procedure using drop down list in PHP - php

I have my drop down form like this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<p>Get a Report of each Gene:<br>
<select name="Prot_Id">
<!--option value="" selected disabled>Select a rating</option-->
<option value="" selected disabled></option>
<option value="chr">chr12:111,843,752-111,889,427</option>
<option value="chr">chr19:17,186,591-17,324,104</option>
<option value="chr">chr2:102,927,962-103,015,21</option>
<option value="chr">chr2:204,732,511-204,738,683</option>
<option value="chr">chr4:123,372,626-123,377,650</option>
<option value="chr">chr4:123,533,783-123,542,212</option>
<option value="chr">chr6:159,456,027-159,466,184</option>
</select>
</p>
<input type="submit" name="submit1" value="Go" />
</form>
I have one MySQL stored procedure Chrome_Seq with one input parameter (eg:chr2:102,927,962-103,015,21 it's the display name for the drop down box).. Now I am writing a PHP page to call this procedure and show the result as table. Here is my PHP code:
<?php
if (isset($_POST['chr'])) {
echo "hi 11";
$id=$_POST['chr'];
echo "<table>";
//connect to database
$connection = mysqli_connect("localhost", "root", "", "KCC_Celiac_Disease");
//run the store proc
echo "hello";
$query= "call Chromo_Seq(".'"'.$id.'")';
$result = mysqli_query($connection, $query) or die("Query fail: " . mysqli_error());
//loop the result set
echo "<tbody>";
// point to the beginning of the array
$check = mysqli_data_seek($result, 0);
$rownew = mysqli_fetch_assoc($result);
foreach($rownew as $k => $v ) {
echo "<th>".$k."</th>";
}
$check = mysqli_data_seek($result, 0);
while ($rownew = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach($rownew as $k => $v) {
echo "<td>".$v."</td>";
}
echo "</tr>"."<br>";
}
echo "</tbody></table>";
}
?>
Whenever I select a value from dropdown it should run the procedure with that parameter and return the value but I am not getting any result in my output. It's blank.

Related

Keep the value selected after fetching the data and query to insert it into database

I have this onchange event on php, if the user choose an option, it fetched the data that is connected on it. However, the page refreshes and the choice of the user disappear. Also, I cannot insert the data to database. I've tried add a form method="post" to the form attribute, but unfortunately it cannot fetch the data.
Thankyou in advance.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$gradeassign = '';
$sectionassign = '';
function getPosts()
{
$posts = array();
$posts[3] = $_POST['sectionassign'];
$posts[4] = $_POST['gradeassign'];
return $posts;
}
if(isset($_POST['addfac']))
{
$data = getPosts();
$insertStmt = $con->prepare('INSERT INTO
facultyagain(sectionnumber,gradelevelassign)
VALUES(:sectionassign,:gradeassign)');
$insertStmt->execute(array(
':sectionassign'=> $data[3],
':gradeassign'=> $data[4],
));
if($insertStmt)
{
echo 'Data Inserted';
}
}
?>
<html>
<head>
<title>Country</title>
</head>
<body>
<form action="trial.php">
Select Your grade
<select name="gradeassign" onchange="this.form.submit()">
<option value="" disabled selected>--select--</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="europe">Europe</option>
</select>
<?php
require 'connection.php';
if(isset($_GET["gradeassign"])){
$gradeassign=$_GET["gradeassign"];
$sql = "SELECT sectionassign FROM sections WHERE gradeassign='$gradeassign'";
$result = $con->query($sql);
echo "<select>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='$row[sectionassign]'>" . $row["sectionassign"]. " </option>";
}
} else { echo "<B>0 Results</B>"; }
echo "</select>";
}
?>
<BR>
<button id="addfac" name="addfac">Add Faculty</button>
</form>
</body>
</html>
You can also store the value in a variable and check to see if the option matches the variable. For example:
<option value="" disabled>--select--</option>
<option value="1" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "1") echo "checked"; ?>>Grade 1</option>
<option value="2" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "2") echo "checked"; ?>>Grade 2</option>
<option value="europe" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "europe") echo "checked"; ?>>Europe</option>
The better way to do it would be to create the whole list with a loop. Bu this should work.

dropdown select value resets after onchange

I am trying to create a dynamic drop-down using php/mysql. For some reason the selected value does not stay selected. The drop-down reset to the initial value. The selected value is used to populate a table on the same php page.
<form action="" method="get">
<select name="user" onchange="this.form.submit();">
<?php
do {
?>
<option value="<?php echo $row["userid"]?>" selected="selected"><?php echo $row["display_name"]?></option>
<?php
} while ($row = mysqli_fetch_assoc($result));
$rows = mysqli_num_rows($result);
if($rows > 0) {
mysqli_data_seek($result, 0);
$row = mysqli_fetch_assoc($result);
}
?>
</select>
You have to add a logic in your code for that.
First when you get data from form, save your dropdown value in a variable.
eg. $user = $_GET['user'];
Now make the following changes in your code.
<form action="" method="get">
<select name="user" onchange="this.form.submit();">
<?php
do {
?>
<option value="<?php echo $row['userid']?>" <?php if($user == $row['user_id']) { echo 'selected="selected"' } ?> >
<?php echo $row["display_name"]?></option>
<?php
} while ($row = mysqli_fetch_assoc($result));
$rows = mysqli_num_rows($result);
if($rows > 0) {
mysqli_data_seek($result, 0);
$row = mysqli_fetch_assoc($result);
}
?>
</select>

I am accessing MySQL table in PHP but it is not executing if condition and directly display the table

The code below is accessing the database table directly, but I want it to display the table content on giving conditions in drop down menu like when I select islamabad in one drop down menu and lahore in other as given in code and press search button, then it display the table flights, but it is displaying it directly
<p class="h2">Quick Search</p>
<div class="sb2_opts">
<p>
</p>
<form method="post" action="haseeb.php">
<p>Enter your source and destination.</p>
<p>
From:</p>
<select name="from">
<option value="Islamabad">Islamabad</option>
<option value="Lahore">Lahore</option>
<option value="murree">Murree</option>
<option value="Muzaffarabad">Muzaffarabad</option>
</select>
<p>
To:</p>
<select name="To">
<option value="Islamabad">Islamabad</option>
<option value="Lahore">Lahore</option>
<option value="murree">Murree</option>
<option value="Muzaffarabad">Muzaffarabad</option>
</select>
<input type="submit" value="search" />
</form>
</form> </table>
<?php
$from = isset($_POST['from'])?$_POST['from']:'';
$to = isset($_POST['to'])?$_POST['to']:'';
if( $from =='Islamabad'){
if($to == 'Lahore'){
$db_host = 'localhost';
$db_user = 'root';
$database = 'homedb';
$table = 'flights';
if (!mysql_connect($db_host, $db_user))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
}
}
mysqli_close($con);
?>
Fix the mysql_ and mysqli_.
Do not repeat the SQL Query to test $result. One is ok.
Fix the case of index - to or To.
Table displayed directly: Hope you are not refreshing the form with the pre-submitted values of your cities. Freshly open the page link, and confirm that $from, $to are really empty. If you are pressing F5 in browser, it may be wrong.

updating sql table for selected check box values

I dynamically create table rows with checkboxes. Check a few of them and then perform and update query on the selected ones. But the problem I face is that only the first selected record gets updated even though I have used foreach loop.
Following is the code.
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'];
$semester = $_POST['promotesemselect1'];
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
foreach($checkbox as $value){
if(isset($checkbox)){
if(($semester%2)==0) {
$strSQL = "UPDATE student SET year='".++$year."', semester='".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester=".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysql_close($db);
?>
Even though I use the foreach loop to get through the array of checkboxes, still only the first checked record gets updated.
This is the html part
<div class="dropdown dropdown-dark">
<select name="promoteyearselect1" id="promoteyearselect1" class="dropdown-select" onfocus="showhidephdmenu()" form="promotionform" required>
<option value="">Select an option</option>
<div id="yearselect1">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
</div>
</option>
</select>
</div>
<div class="dropdown dropdown-dark">
<select name="promotesemselect1" id="promotesemselect1" class="dropdown-select" form="promotionform" required>
<option value="">Select an option</option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
<option value="9">9th</option>
<option value="10">10th</option>
</select>
</div>
<button id="promotego" class="login-button" style=" position:relative; padding: 0 0 0; " onclick="getpromotestudents()"></button>
</div>
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">
The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<input type="submit" value="Promoted" class="button black"></input>
Passed Out
</div>
</form>
This is the PHP that gets the records and generates checkboxes.
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>";
echo "</tr>";
$i++;
}
Here is the modified code that finally worked for me, I added spaces in the if($semester % 2 != 0)
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'] + 1 ;
$semester = $_POST['promotesemselect1'] + 1;
$con = mysqli_connect("localhost","root","","university") or die("Error " . mysqli_error($con));
foreach($checkbox as $value){
if(isset($checkbox)){
// echo $value;
if( $semester % 2 != 0) {
// echo $value;
$strSQL = "UPDATE student SET year='".$year."', semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysqli_close($con);
?>
I didn't found any checkbox with name 'pr' in your code..If there is any ..please make it an array and try
like <input type="checkbox" name="pr[]">

PHP- Fetch from database and store in drop down menu html

I can't seem to get the following code to make a dropdown menu that contains data from a mysql database. The "include('connect.php');" connects to the mysql database and I know it works on separate pages. Any suggestions?
Below is the entire code.
listCustomer
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name=dropdown value=''>Dropdown</option>";
while($r = mysql_fetch_array($result))
{
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
}
echo "</select>";
?>
<BR>
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
From the looks of things, you're missing an opening option tag, so it's just outputting "Dropdown" as a line of text.
Edit
Just to be completely transparent, because I did not have connect.php, I had to add my own DB connections. My whole page looked thusly:
<?
//Adding to display errors.
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR />
<?php
// BEGIN ADDED CONNECTION HACKY GARBAGE
$con=mysql_connect("localhost","root","root");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selected = mysql_select_db("sample",$con)
or die("Could not select examples");
// END ADDED CONNECTION HACKY GARBAGE
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
<BR />
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
First off, you are missing an option opening tag, as correctly mentioned by stslavik. But this is not causing the issue here as it seems (it's auto-corrected by the browser - in my tests atleast).
Secondly, this wont work (problem causer):
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
You should use
echo "<option value=".$r["Cnum"].">".$r["CName"]."</option>";
or, as I always prefer single quotes to enclose echo or print output strings:
echo '<option value='.$r['Cnum'].'>'.$r['CName'].'</option>';
Third alternative (complex syntax: What does ${ } mean in PHP syntax?)
echo "<option value={$r["Cnum"]}>{$r["CName"]}</option>";
assuming you get data from the database try this
echo "<option value={$r['Cnum']}>{$r['CName']}</option>";
try,
echo "<option value=' . $r['Cnum'] . '>' . $r['CName'] . '</option>";
instead of
echo "<option value=$r[Cnum]>$r[CName]</option>";

Categories