multiple dynamic drop down submission on button click to mysql table - php

hey guys i am working on a small project for my college. it consists of a table which is dynamic(linked to mysql table) and one cell in every record is a dynamic drop down(all are linked to mysql table). and the user has to choose from a list of drop down values for each drop down generated and it can also be left blank. here is the php code for that:
<form class="appnitro" method="post" action="">
<div class="form_description">
<center><h2>NOMINATE ENTRY</h2></center>
<p><center><font size='3'>
<?php
$con=mysqli_connect("localhost","user",pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dept = $_POST['department'];
$class = $_POST['class'];
$result = mysqli_query($con,"SELECT * FROM prizemaster");
$result1 = mysqli_query($con,"SELECT * FROM studentmaster WHERE dept='$dept' and class='$class'");
echo "<table border='1'>
<tr>
<th>Prize ID &nbsp &nbsp &nbsp &nbsp</th>
<th>Prize Name &nbsp &nbsp &nbsp &nbsp </th>
<th>Name &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp </th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['prizeid'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><select name='name'>";
echo "<option></option>";
while($drop = mysqli_fetch_array($result1))
{
echo "<option value='".$drop['name']."'>" . $drop['name'] . "</option>";
}
mysqli_data_seek($result1, 0);
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?></center></font></div>
<p>
<center><button type="submit" formaction="stnomins.php">Nominate</button></center>
</form>
the above is the form and when the nominate button is clicked i want this code to be executed for each and every drop down value selected:
<?php
$con=mysqli_connect("localhost","user","pass","db");
$myname = $_POST['name'];
$sql2="SELECT * FROM studentmaster WHERE name='$myname'";
$result = mysqli_query($con,$sql2)or die(mysqli_error());
$row = mysqli_fetch_array($result);
$mydept=$row['dept'];
$myclass=$row['class'];
$myregno=$row['regno'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="INSERT INTO studenttransaction (`transid`, `date`, `prizeid`, `regno`, `name`, `class`, `department`, `status`) VALUES ('' , CURRENT_TIMESTAMP() , '', '$myregno', '$myname', '$myclass', '$mydept', '1')";
if (!mysqli_query($con,$sql1))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
kindly help me out i need to submit it in 2 days. please explain with code because i am new to php and not fully known to it

I have updated both of your html & php code, please have a look :
In form file:
echo "<td><select name='name[]'>"; // added [] here to make it array
echo "<option value=''>Select student</option>"; // added value & option item
These above lines of code have been modified accordingly in the file below
<form class="appnitro" method="post" action="">
<div class="form_description">
<center><h2>NOMINATE ENTRY</h2></center>
<p><center><font size='3'>
<?php
$con=mysqli_connect("localhost","user",pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dept = $_POST['department'];
$class = $_POST['class'];
$result = mysqli_query($con,"SELECT * FROM prizemaster");
$result1 = mysqli_query($con,"SELECT * FROM studentmaster WHERE dept='$dept' and class='$class'");
echo "<table border='1'>
<tr>
<th>Prize ID &nbsp &nbsp &nbsp &nbsp</th>
<th>Prize Name &nbsp &nbsp &nbsp &nbsp </th>
<th>Name &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp </th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['prizeid'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><select name='name[]'>";
echo "<option value=''>Select student</option>";
while($drop = mysqli_fetch_array($result1))
{
echo "<option value='".$drop['name']."'>" . $drop['name'] . "</option>";
}
mysqli_data_seek($result1, 0);
echo "</select></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?></center></font></div>
<p>
<center><button type="submit" name="nominate" formaction="stnomins.php">Nominate</button></center>
</form>
Slightly updated your PHP code. Started a loop for each drop-down of names if button is clicked/submitted.
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['nominate'])){
foreach($_POST['name'] as $key => $myname){
//$myname = $_POST['name'];
$sql2="SELECT * FROM studentmaster WHERE name='$myname'";
$result = mysqli_query($con,$sql2)or die(mysqli_error());
if($row = mysqli_fetch_array($result)){
$mydept=$row['dept'];
$myclass=$row['class'];
$myregno=$row['regno'];
$sql1="INSERT INTO studenttransaction (`transid`, `date`, `prizeid`, `regno`, `name`, `class`, `department`, `status`) VALUES ('' , CURRENT_TIMESTAMP() , '', '$myregno', '$myname', '$myclass', '$mydept', '1')";
if (!mysqli_query($con,$sql1)){
die('Error: ' . mysqli_error($con));
}
}//if mysqli_fetch_array condition closed
}// for loop closed
}// if submit button(nominate) closed
mysqli_close($con);
?>
Hope this will work for you.

its working fine. I have another doubt is that how to echo the value of drop down when a drop down value is selected.Anybody who knows the answer of it, kindly provide the solution of it.

Related

How to insert mysql database in a new file?

I would like to know how can i put the table from mysql in a new file.php.
I want the MySql table to be on the page.
This is my code that inserts data in MySql.
<?php
// Create connection
$con = mysqli_connect("host", "id_", "password", "xxxxxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Task = $_POST['Task'];
$Date = $_POST['Date'];
$Desc = $_POST['Desc'];
$sql = "INSERT INTO tasklist (Task, Date, Description)
VALUES ('$Task', '$Date', '$Desc')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
<html>
<body>
<form action="addtask.php" method="post">
Task: <input type="text" name="Task">
Date: <input type="text" id="datepicker" name="Date">
Decrption:<textarea type="text" name="Desc"></textarea>
<input type="submit" value="submit">
</form>
</body>
</html>
Try this code:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
also u can try w3schools sample code :
Display the Result in an HTML Table
The following example selects the same data as the example above, but will display the data in an HTML table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The output of the code above will be:
first code comes from "Jonnny" in this article

Updating data from checkbox clicked

My Code so far. The data gets pulled correctly
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Request");
echo "<table border='1'>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Prayer Request</th>
<th>Deactivate Request</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Reg_F_Name'] . "</td>";
echo "<td>" . $row['Reg_L_Name'] . "</td>";
echo "<td>" . $row['Reg_Request'] . "</td>";
echo "<td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"".$rows['Reg_ID']. "\" /></td>";
echo "</tr>";
}
echo "</table>";
echo
"<form action='' method='post'>
<input type='submit' name='use_button' value='Update' />
</form>";
if(isset($_POST['use_button']))
{
echo "hey";
$del_id = $_POST['checkbox'];
$detectinglocations = 'your database table name';
foreach($del_id as $value){
$sql = "Update Request set Reg_Status=0 WHERE Reg_ID='".$value."'";
$result = mysql_query($sql);
}
}
mysqli_close($con);
?>
Nothing Happens when I Click Submit. I am wanting it to Update the reg_Status to 0 for every check box that is click. So whats my problem. Thank you in advance for helping!
try adding an input hidden field with same name as the checkbox name before each checkbox and with value 0 .
The checkbox doesnt get posted when not checked.

Change table content using a link

I am new to PHP and I made a simple program where you can apply your name and age, it will take the data to the database and the table will be added with a new row.
I want to add a new column where you can click "change", only the data from that particular row will show up in a few textboxes and can be changed. when pressing submit I want to use the UPDATE function to update the records.
example/plot:
Mike Towards 23 Change
Tyler Frankenstein 24
Change Sophie Baker 22
Change
I want to change the age of Sophie Baker to 24 so I press Change on that row.
Now I only want to get the data from that row and make some changes.
The code I have this far:
Drawing the table above the input fields and the input:
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="insert.php" method="post"><br />
<input type="text" name="firstname"> Firstname <br />
<input type="text" name="lastname"> Lastname <br />
<input type="text" name="age"> Age
<p><input type="submit"></p>
</form>
</body>
</html>
Parser:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
mysqli_close($con);
?>
I have tried a few things, but I cant figure out how to show the content on the row I want to select.
Change the actual data with the update function won't be the problem, so I only need help to get the actual data from the correct row.
you'd need to select with the primary key of that table if any exists. if not you should create one. I assume you have a primary key named PersonID:
$query = "SELECT * FROM Persons WHERE PersonID = '" . ($_GET['PersonID']) . "'";
to add the edit button:
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th><th>Action</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href = '?PersonID=" . $row['PersonID'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
I assume you have a column named "id".
you can do the following:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// when you are in "edit mode" just display the row you will edit row
if (isset($_GET['id'])
$result = mysqli_query($con,"SELECT * FROM Persons where id = ".(int)$_GET['id']);
else
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href='?id=" . $row['id'] . "'>change</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="update.php" method="post"><br />
<input type="hidden" name="id" value="<?php echo isset($_GET['id']?$_GET['id']:'') ?>" />
<input type="text" name="firstname" value="<?php echo isset($row['FirstName'])?$row['FirstName']:'' ?>"/> Firstname <br />
<input type="text" name="lastname" value="<?php echo isset($row['LastName'])?$row['LastName']:'' ?>"/> Lastname <br />
<input type="text" name="age" value="<?php echo isset($row['Age'])?$row['Age']:'' ?>"/> Age
<p><input type="submit"></p>
</form>
</body>
</html>
update.php (handle both insertion and update):
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['id'])
$sql="UPDATE Persons set FirstName = ?, LastName = ?, Age = ?
WHERE id = ".(int)$_POST['id'];
else
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)";
$sth = mysqli_prepare($con, $sql);
$sth->bind_param($_POST[firstname],$_POST[lastname],$_POST[age]);
if (!$sth->execute())
{
die('Error: ' . mysqli_error($con));
}
echo "1 record ".(isset($_POST['id']?'modified':'added')." to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";

insert output from mysql query into html table one after another

heloo, i want to serarch particular row from mysql database and same should be displayed on html table. I have tried the below code but it only gives the single row which is result of current query, previous row get overwritten. I am fetching a row for particular id,next time when i give another id,another row should be fetched and it should be added to the table next to previous one..
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
<tr>
ProductID: <input type="number" name="ProductID">
<input type="submit" value ="Go">
</form>
</tr>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","m70830807","Inventory");
// Check connection
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db("Inventory",$con);
$ID=$_POST['ProductID'];
//echo $ID;
$result = mysqli_query($con,"SELECT ProductID, ProductName, UnitPrice FROm Products_Sold where ProductID =" .$ID);
echo"<table border = '1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>UnitPrice</th>
</tr> ";
//$row=mysqli_fetch_array($result);
//$c1= $row['ProductID'];
//$c2=$row['ProductName'];
//$c3=$row['UnitPrice'];
//echo $c1;
//echo $c2;
//echo $c3;
//$ins= mysqli_query($con,"insert into Temp (ProductID,ProductName,UnitPrice) values ('%d','%s','%f')", $c1,$c2,$c3);
//$fetch=mysqli_query($con,"select ProductId,ProductName,UnitPrice from Temp");
while( $row = mysqli_fetch_array($result))
{ echo "<tr>";
echo "<td>". $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] ." </td>";
echo "<td>" . $row['UnitPrice'] . "</td>";
echo "</tr> ";
}
echo "</table>";
mysqli_close($con);
?>
If you need to do this within a user session (one user has one list. Another got different) so you need to use session
In your example -
<?php
session_start();
$con=mysqli_connect("localhost","root","m70830807","Inventory");
// Check connection
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db("Inventory",$con);
$ID=$_POST['ProductID'];
$_SESSION['ids'][mysql_escape_string($ID)] = array();
//echo $ID;
$result = mysqli_query($con,"SELECT ProductID, ProductName, UnitPrice FROm Products_Sold where ProductID IN (\"" . implode('","', usort(array_keys( $_SESSION['ids']))). '");');
echo"<table border = '1'>
<tr>
<th>
ProductID
</th>
<th>
ProductName
</th>
<th>
UnitPrice
</th>
</tr>
";
while( $row = mysqli_fetch_array($result)) { echo "
<tr>
"; echo "
<td>
". $row['ProductID'] . "
</td>
"; echo "
<td>
" . $row['ProductName'] ."
</td>
"; echo "
<td>
" . $row['UnitPrice'] . "
</td>
"; echo "
</tr>
"; } echo "
</table>
";
mysqli_close($con);
?>
You need to use ajax and jquery to do this.
send request via ajax and get response as your row. Manipulate the table using jquery to append in the existing set of records

How do I reduce the number of variables and connections for php connecting to mysql server?

I am trying to reduce the number of connections that this page makes. Everything I read says that only one connection should be enough however if I remove the additional connections the page doesn't connect to my server and provide me the results I am looking for. Also one of the queries I am using twice but if I call the original query the second time it also does not work.
What am I doing wrong?
<?php
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequnce, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysql_query($sql);
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysql_query($sql2);
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysql_query($sqlstart);
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysql_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysql_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>
Once a connection is open in a page you don't need to re-open it for each query. You can simply remove all the statements that create a connection and select the database, except the first one.
Note you're using mysqli to open the connection, but mysql to query it. The two sets of functions are not interchangeable: use mysqli as 'mysql' is deprecated and support will be removed in the future.
Try this:
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequence, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysqli_query($con,$sql2) or die(mysqli_error($con));
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysqli_query($con, $sqlstart) or die(mysqli_error($con));
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysqli_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>

Categories