Delete MySQL Database selection from dropdown menu in PHP - php

I'm currently working on a knowledge base for articles for our schools info center. Currently I'm making a page for moderators to delete articles. The page grabs all data from the "articles" table in the database to display it in a dropdown menu. The user can then select whichever and press delete. Which I intend to have said button take the selected ID and remove it from the database. However it will not delete.
Code:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
{
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
}
?>
<form method="post" action="deleteArticles.php">
<select name="articles" multiple="multiple">
<?php
$sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
while ($row = mysqli_fetch_assoc($sql))
{
echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
}
?>
</select>
<input type="submit" value="Delete" name="Delete" />
</form>

You missed to close your open select tag. You also didn't add multiple attribute to allow multiple selection.
<select name="articles" multiple="multiple">
<?php
$sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
while ($row = mysqli_fetch_assoc($sql))
{
echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
}
?>
</select>
Uneeded {} wrapping removed.
And this:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
{
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
}
?>
To:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
?>
Since it is multiple selection, change select name to articles[]
Like:
<select name="articles[]" multiple="multiple">

Related

insert dynamic dropdown values in the database on button click in php

i am dynamically adding the values in the dropdown . After selecting the value in the dropdown and entering text in the textbox, both textbox value and dropdown value has to be entered in the database on button click. But my code is not working properly ie only textbox value is inserted in the database but not dropdown selected vlaue. Please correct my code
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label style="margin-left:260px;width:170px"><h3 >Topic:</h3><br></label><br>
<select name="topic" style="margin-left: 282px;margin-top: -17px;">
<option value=""> -----Select----- </option>
<?php
$records = mysql_query("SELECT topic FROM topic ");
while ($row = mysql_fetch_array($records)){
echo "<option value=\"\">" . $row['topic'] . "</option>";
}
?>
</select>
<label style="margin-left:260px;width:170px"><h3 >Enter Crime Key Point:</h3><br></label><br>
<textarea name="details" id="details" rows="14" cols="60" style="margin-left:112px"><?php if(isset($_POST['details'])){echo htmlspecialchars($_POST['details']);}?>
</textarea><br><br>
<br><br><input type='submit' name='submit' value='Post' style='margin-left:305px;'>
</form>
if(isset($_POST["submit"]) ){
//if ( isset( $_POST['topic'] )){
//if(!empty($_POST['CarList'])){
$story = $_POST['details'];
$topic = $_POST['topic'];
echo $topic;
$sql = "SELECT `registered` FROM `user` WHERE `name`='{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$register=$row['registered'];
if ($register==1)
{
$sql = "INSERT INTO `stories`(`stories`,`name`,`topic`,`date/time`) VALUES ('$story','{$_SESSION['name']}','$topic',now())";
$result = mysql_query($sql);
echo $result;
if (! $result)
{
//echo "Story is not inserted. Please avoid special characters.";
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
$sql = "select count(*) from stories where `date/time`=DATE(NOW()) AND `name` = '{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$count=$row['count(*)'];
if ($count<3)
{
$sql = " INSERT INTO `stories`(`stories`,`name`,`date/time`) VALUES ('$story','{$_SESSION['name']}',now())";
$result = mysql_query($sql);
if (! $result)
{
echo "Story is not inserted";
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
echo '<img src="images/animated-star-image-0009.gif" width="25px"/>Please Register to enter more than 3 stories per day';
}
}
}
}
}
?>
The line:
echo "<option value=\"\">" . $row['topic'] . "</option>";
change it to:
echo "<option value='".$row['topic']."'>" . $row['topic'] . "</option>";
You are passing empty values for the topic parameter. Setting up a correct value will ensure that you are inserting the correct user input in the database.
For future you can debug this easy by outputting your POST content before executing the SQLinsert.
That will fix your issue, but there are several other things you might consider changing, one of them is the deprecated mysql_ extension, switch to mysqli or PDO.

Trying to update a single item's quantity when an item is "purchased" from my store, but every item in my table is updated. Why?

Please understand- I am not experienced with PHP. But I know I am close to figuring this out.
I have a table, generated by a while loop (getting data from a MySQL database), that gives the customer a list of albums from an artist. I want the customer to be able to input the quantity of the album they wish to purchase, and have the database update appropriately. I can get the code to loop through and update every album in my table (based on user input), but that is obviously not what I want. How can I make it so only ONE album is updated at a time??
Here is my code:
<div id = "MusicSearch"><h4>Search For Music</h4></div>
<div id="search">
<form method="post" action="get-records.php?go" id="searchform">
<input type="text" name="artistName">
<input type="submit" name="submit-form" value="Search">
</div>
<?php
if(isset($_POST['submit-form'])){
$artistName = $_POST['artistName'];
if(isset($_GET['go'])){
if(preg_match("/^[A-Za-z]+/", $_POST['artistName'])){
include 'include/connect.php';
$sql = "
SELECT y.artistName
, x.albumName
, x.albumID
, x.cost
, x.stock
FROM album x
JOIN artist y
ON x.artistID = y.artistID
WHERE y.artistName LIKE '%" .$artistName. "%'
";
$result = $con->query($sql);
echo '<table><tr><th>Artist</th><th>Album</th><th>Cost</th><th>Stock</th><th>Quantity</th></tr>';
?>
<?php
while ($row = $result->fetch_array()) {
$albumName=$row['albumName'];
$cost=$row['cost'];
//$albumID=$row['albumID'];
$stock=$row['stock'];
echo '<tr>';
echo '<td>' . $artistName . '</td>';
echo '<td>' . $albumName . '</td>';
echo '<td>' . $cost . '</td>';
echo '<td>' . $stock . '</td>';
?>
<td><form method="post" action="get-records.php">
<input type="hidden" name="albumID[<?php echo $row['albumID']; ?>]" value="<? echo $row['albumID']; ?>"></input>
<input type="number" name="quantity[<?php echo $row['albumID']; ?>]" value="<?php echo $row['quantity']; ?>"></input>
<input type="submit" name="purchase-form" value="Purchase"/></form></td>
<?php
}
echo "</table>";
}
}
}
if(isset($_POST['quantity'])){
foreach($_POST['albumID'] as $key => $id){
$quan = mysqli_real_escape_string($con, $_POST['quantity'][$key]);
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = albumID";
try{
$result = $con->query($q);
if (!$result)
echo "Error, try again " . mysqli_error($con);
if(is_null('id'))
throw new Exception('Error. Try again');
}
catch (Exception $ex) {
echo '<div class="error">' . $ex->getMessage() . '</div>';
}
}
}
?>
replace your update query with this UPDATE album SET stock = 'stock-".$quan."' WHERE albumID = '".$id."'
May you need to use $_POST['albumID']'s value Instead of albumID, here
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = $id";
albumID = albumID is true for all rows that's why its updating all records

PHP dropdown list

I am trying to get the user to pick from the dropdown menu. When the user clicks on the selected item they will click a button and show the results.
I haven't been able to display the information onto the page.
$sql = "select * from Owner";
echo'<form action="index1.php" method="post">';
echo '<select name="bid" id="bid">';
foreach($conn->query($sql) as $row) {
echo '<option value=" ';
echo $row["id"];
echo ' ">';
echo $row['LastName'];
echo '</option>';
}
echo'</select>';
echo'<br><input type="submit" value="Show Info"><br>';
echo'</form>';
//check if submit button has been clicked
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['bid'];
try{
$sql = "select Owner.FirstName, Owner.LastName,MarinaSlip.BoatName from Owner, MarinaSlip where Owner.OwnerNum = MarinaSlip.OwnerNum
and Owner.FirstName = $id";
foreach($coon->query($sql) as $row){
echo$row['FirstName'].' '.$row['LastName'].' '.$row['BoatName'].'<br>';
}
}//end of try
catch(PDOExeption $e){
echo "Error: ".$e -> getMessage();
}
}

Adding a validation check to a form in a while loop php

I have a form which displays like this:
Event Name : Drop down menu
I am trying to add a check that ensures that each event produced by the while loop has a student assigned to it - by selecting from the drop down menu.
I have attempted adding a check for this but its not making a difference - it loads form action page 'savecompetitors'.
I have got this for php so far:
<?php
session_start();
require_once 'db/connect.php';
require_once 'db/checkuserloggedin.php';
include 'db/header.php';
echo $_SESSION['Username'] . ' logged in successfully';
echo '<h3> Entry form </h3>';
//Query to display all events
if ($event_result = $con->query("SELECT Name FROM event")) {
echo "<form method =\"POST\" action=\"savecompetitors.php\">";
echo '<table>';
while ($row = $event_result->fetch_assoc()) {
echo '<tr>';
echo '<td>';
echo $row['Name'] . ' ';
echo '</td>';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Forename, Surname, Student_ID " .
"FROM student, teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")
) {
if ($student_result->num_rows) {
echo '<td>';
echo "<select name ='" . $row['Name'] . "'>";
while ($row1 = $student_result->fetch_assoc()) {
echo '<option value="" style="display:none;"></option>';
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
if (isset($_POST['submit'])) {
if (empty($_POST['Student_ID'])) {
$error = 'A student must be selected for every event';
}
}
}
echo "</select>";
echo '</td>';
echo '</tr>';
}
}
}
echo '</table>';
echo '<input type="submit" name="submit" value ="Submit" >';
echo '<input type="reset" value ="Reset">';
echo '<span class="error"><?php echo $error;?></span>';
echo '<span class="error"><?php echo $success;?></span>';
echo "</form>";
} else {
echo 'No student records available';
}
savecompetitors php:
<?php
require_once 'db/connect.php';
$error = '';
$success = '';
$event_result = $con->query("SELECT Event_ID, Name from event");
while ($row = $event_result->fetch_assoc()) {
$eventname = str_replace(' ', '_', $row['Name']);
print_r($row);
$con->query("INSERT INTO competitors (Event_ID, Student_ID) VALUES (" . $row['Event_ID'] . ", " . $_POST[$eventname] . ") ");
$success = 'Entry form has been successfully saved and students are entered as competitors for their submitted events';
}

Option get data from DB

I have got this table in my Database:
**train_information**
train_id
country_id
user_id
train_name
tare_weight
number_of_bogies
number_of_axles
wheel_diameter_min
wheel_diameter_max
And then i have 2 .php pages (1 is only for classes)
Selector.php
<!--Selector-->
<form name='form' id='selector'>
<?php
$selector = $database->selector();
?>
<select onchange= "mySelection()" id ="selector" name="selector">
<option selected="true" disabled="disabled">Selecteer een trein</option>
<?php
foreach ($selector as $selector) {
print "<h3>" . $selector['train_id'] . "==" . $selector_id . "</h3>";
if ($selector['train_id'] == $selector_id) {
echo "<option value=" . $selector['train_id'] . " selected='selected'> " . $selector['train_name'] . "</option>";
} else {
echo "<option value=" . $selector['train_id'] . "> " . $selector['train_name'] . "</option>";
} }
?>
</select>
</form>
And then the class.php
function selector() {
$sql = "SELECT train_id, train_name FROM train_information";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
The selector shows the train names in the selection. so that is good.
But i want that when i select it, and press a button like: Select. That it select the information of that selected train and shows it on the page.
And i don't only want to show 1, but if i would like to select a other train after that, it shows both trains information on the page.
How do i do this?
You can do following
Add this Method to class.php
function select_train_details($trainId) {
$sql = "SELECT * FROM train_information where train_id = " . $trainId;
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
Add Following to selector.php
<form name='form' id='selector'>
<?php
$selector = $database->selector();
if (isset($_POST['selector'])) {
$selectorDetail = $database->select_train_details();
}
?>
<select onchange= "this.form.submit" id ="selector" name="selector">
<option selected="true" disabled="disabled">Selecteer een trein</option>
<?php
foreach ($selector as $selector) {
print "<h3>" . $selector['train_id'] . "==" . $selector_id . "</h3>";
if ($selector['train_id'] == $selector_id) {
echo "<option value=" . $selector['train_id'] . " selected='selected'> " . $selector['train_name'] . "</option>";
} else {
echo "<option value=" . $selector['train_id'] . "> " . $selector['train_name'] . "</option>";
}
}
?>
</select> </form> <?php if (isset($selectorDetail)) {
echo "<pre>";
$selectorDetail; } ?>

Categories