I need to create a function which retrieves my data from my database into a drop down list, then choose and remove the selected data. I have my drop down list done & working but I'm experiencing some error with my 'Remove' function.
<body>
<?php
//connecting to database
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
//dropdown list to retrieve sentence
$sql = "SELECT words FROM sentence";
$result = mysql_query($sql);
echo "<select name
='dropdownlist'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['words'] ."'>" . $row['words'] ."</option>";
}
echo "</select>";
?>
<form method="post" action="remove.php">
<input type="submit" value="Remove" />
</form>
<a href="index.php" >View list</a>
</body>
Followed by another php file
<?php
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$dropdownlist1 = $_POST['dropdownlist'];
$dropdownlist2 = $dropdownlist1.value;
if(isset($_GET['id'])) {
$mysql_query("DELETE FROM 'words' WHERE id = $dropdownlist2");
header("location: index.php");
exit();
}
?>
Move your Select box or dropdown inside the form tag,
<form method="post" action="remove.php">
<select name ='dropdownlist'>
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value='<?php echo $row['words'];?>'><?php echo $row['words'];?></option>
<?php } ?>
</select>
<input type="submit" value="Remove" />
</form>
in php,
if(isset($_POST['dropdownlist'])) {
$dropdownlist1 = $_POST['dropdownlist'];
mysql_query("DELETE FROM `sentence` WHERE `words` = '$dropdownlist1' ");
header("location: index.php");
exit();
}
Note: Use mysqli_* or PDO functions instead of using mysql_* functions(deprecated)
Related
I create a dropdown list to select values:
<form action="." method="post" id="aligned">
<input type="hidden" name="action" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
die('Could not connect: '. mysql_error());
mysql_select_db($db);
$selected= mysql_query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = mysql_query("select * from countries order by countryName");
if($selectedrow = mysql_fetch_array($selected)){
echo "<option selected value=\"VALUE\">" . $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value =\"VALUE\">". $row['countryName']."</option>";
}
//echo "</select>";
?>
</select><br>
In another php file as below, I was trying to store the selected value for Country, but nothing is stored, why?
<?php $country_name = $_POST["selected"];
echo $country_name;//it always print out 'VALUE'-I guess it means null.
?>
You should use
echo "<option value ='".$row['countryName']."'>". $row['countryName']."</option>";
And I want to add something, MySQL is deprecated in PHP5 and removed from PHP7. what is your PHP version. If you use PHP 5 or later use mysqli.
My problem now:
once I echo the value from the database its woking good. but when I submit the form I got an empty value of the selected option.
Can any one help. I tried to used {} in he value code but it did not work.
What I want :
Set the the value of the selected option as it is on the database to insert it into another table.
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="" selected>--select-- </option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['centerName'].'">'.$row['centerName'].'</option>';
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
Try this
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="0" selected>--select--</option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$name = $row['centerName'];
echo "<option value='$name'> $name </option>";
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
</select>
You will have to "expand" your select query to include the ID of the row, and then instead of $row['centerName'] use $row['id'] (or what your ID column is named) in the value argument of the option element, and not the 'centerName'. If I understood correctly what you want, this should be it.
Edit: And do switch to mysqli_, mysql_ has been deprecated.
try to write like this:
echo '<option value="',$row["centerName"],'">',$row["centerName"],'</option>';
Warning:
Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead.
Solution
I recreated your issue and enhanced your code using mysqli extensions, and it's working fine. Take a look at the following code,
<?php
if(isset($_POST['submit'])){
// display submitted option
echo $_POST['CenterTO'];
}
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbName = "stackoverflow";
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $dbName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Execute query
$result_set = $connection->query("SELECT centerName FROM jeCenter");
?>
<form action="form_page.php" method="POST">
<select name="CenterTO">
<option value="" selected>--select-- </option>
<?php
// Check if number of rows is greater than zero or not
if($result_set->num_rows > 0){
// Loop through each record
while($row = $result_set->fetch_assoc()){
?>
<option value="<?php echo $row['centerName']; ?>"><?php echo $row['centerName']; ?></option>
<?php
}
}else{
?>
<option value="none">No data</option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Close connection
$connection->close();
?>
I have two input text fields where user has to specify the begin and end of the fly.
<input type="text" name="start" placeholder="Start destination">
<input type="text" name="end" placeholder="End destination">
I would like to change that and give user to chose start and end destination from database.
<select>
<option value="$id">$name</option>
</select>
I know how to get done if i read database and input values manually, but i know its posible if page loads and execute my SELECT QUERY.
So i have to create dropdown list and fill that with a values from database.
This dropdown list has to be filled when the page load.
Some idea for this ???
I am working with php.
Thank you in advance !!
EDIT : I get done this only with php.
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "flights";
$conn = mysql_connect("$db_host","$db_username","$db_password") or die ("no conn");
#mysql_select_db("$db_name") or die ("no database");
if ($conn = true) {
// echo "";
}
//cyrilic
$sql = "SET NAMES 'utf8'";
mysql_query($sql);
//query for end
$sql="SELECT Distinct end from flights_table;";
$result=mysql_query($sql);
echo "<select name=\"city\">";
echo "<option>end destination</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['end']."'>".$row['end']." </option>";
}
echo "</select>";
?>
This php fires when page loads. Those select options i have putted in a form, and when form is submited, it fires php itself. I am getting selected options this way :
$startfly=$_POST['end'];
I am doing this for starting the flight :)
Thank you guys !
Try this :
At the top of page include your database connection file :
<?php
require "connection.php";
?>
Then :
<?php
$selectStart = "Start : <select name='start'>";
$selectEnd = "End : <select name='end'>";
$query = mysql_query("SELECT * FROM someTable ORDER BY dateField ASC");
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$selectStart .= "<option value='".$row['startItem']."'>".$row['startItemName']."</option>";
$selectEnd .= "<option value='".$row['endItem']."'>".$row['endItemName']."</option>";
}
}
$selectStart = "</select>";
$selectEnd = "</select>";
?>
In your HTML :
<form action='destinationPage.php' method='post'>
<?php
echo $selectStart;
echo $selectEnd;
?>
<input type='submit' value='Submit' />
</form>
i want to delete a table row from my database with MySQL and PHP. I have searched on the internet and I can't figure out what I'm doing wrong. I have the feeling I'm close.
If I go over the delete link there is a link showing with the ID number of the row to delete. But if I click it, it isn't working.
This is my code for admin.php
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Kan niet inloggen");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html><head>
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link href="../css/layout.css" rel="stylesheet" type="text/css"></head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo"><img height="140" src="../images/boyslogo.png"> </div>
<div class="titelpagina">Vroomshoopse Boys E2 admin panel</div>
<div class="uitloggen">Uitloggen</div>
</div>
<div class="content">
<div class="teamstoevoegenvak">
<div class="titelbalk">
<h1>Voeg teams toe</h1>
<form style="border:0px; margin:0px; padding:0px"; action="e2admin.php" method="POST">
<input width="400" maxlength="400" type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form></div>
</div>
<div clas="toegevoegdeteamsvak">
<div class="titelbalktoege">
<h1>Toegevoegde teams</h1>
</div>
<div class="deteams">
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
</div>
</div>
</div>
<div id="volgendewedstrijd"> <form action="" method="post">
<select name="dropdown">
<?php
mysql_data_seek($result, 0);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="">' . $row['Team'] . '</option>';
}
}
?>
</select>
</form></div>
</div>
</body>
</html>
The piece of code where the delete is, is this:
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
And this is my delete.php:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
echo "Team is deleted";
header('location: e2admin.php');
?>
What am I doing wrong?
You are using del as a param in the link
<a href="delete.php?del='.$row['ID'].'">Delete<br>
This needs to be closed as
Delete<br>
And in the delete script you need to get it as
$id = (int)$_GET["del"];
and use in the query as
mysql_query("DELETE FROM e2teams WHERE ID = $id");
This:
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
Should be:
mysql_query("DELETE FROM e2teams WHERE ID = ".$_GET['del']."");
Because of:
<a href="del.php?del='.$row['ID'].'"> //the get var name is: del
You can access a variable inside a array between quotes:
Change the following line
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
to
mysql_query("DELETE FROM e2teams WHERE ID = " . $_GET['id']);
This is a security risk and you are acceptable to SQL injections. Please google: "php sql injections".
I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>