I'm trying to delete an entry from my database using an HTML form. However, when it's submitted, the entry doesn't get deleted from the database and no error code is displayed to say why.
Could somebody possibly let me know if I'm missing something from my code, just in case I've over-looked something?
Thank you.
<form method="post" action="./removeBook.inc.php">
<select name="books">
<option>Please select the Book you wish to delete:</option>
<?php
try {
$dsn = "mysql:host=csdm-mysql;dbname=db1001550_book_management";
$username = "1001550";
$password = "1001550";
// try connecting to the database
$con = new PDO($dsn, $username, $password);
// turn on PDO exception handling
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// enter catch block in event of error in preceding try block
echo "Connection failed: " . $e->getMessage();
}
try {
$sql=("SELECT * FROM books");
$results = $con->query($sql);
if ($results->rowcount() == 0) {
echo "<p>No books found. </p><br />";
} else {
foreach ($results as $row) {
$book_id=$row['book_id'];
echo "<option value=\"".$book_id."\">".$book_id."</option>";
}
}
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
}
mysql_close();
?>
</select>
<input type="submit" name="submit" value="Remove Book" style="width:auto;">
</form>
And here is the code within the form submitted page:
<?php
$host="csdm-mysql"; // Host name
$username="1001550"; // Mysql username
$password="1001550"; // Mysql password
$db_name="db1001550_book_management"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("Cannot select DB");
if (isset($_POST['books'])) {
$books=$_POST['books'];
}
// Remove data from database
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
// if successfully deleted from database, prompt will say book was deleted.
if ($result) {
print "<script type=\"text/javascript\">";
print "alert('Book has been deleted successfully!')";
print "</script>";
} else {
print "<script type=\"text/javascript\">";
print "alert('Book was not deleted')";
print "</script>";
}
// close connection
mysql_close();
?>
<form method="post" action="./removeBook.inc.php">
<select name="books">
<option>Please select the Book you wish to delete:</option>
<option value='B0001'>B0001</option><option value='B0002'>B0002</option><option value='B0003'>B0003</option><option value='B0004'>B0004</option><option value='B0005'>B0005</option><option value='B0006'>B0006</option><option value='B0007'>B0007</option><option value='B0008'>B0008</option><option value='B0009'>B0009</option><option value='B0010'>B0010</option><option value='B0011'>B0011</option><option value='B0012'>B0012</option><option value='B0013'>B0013</option><option value='B0014'>B0014</option><option value='B0015'>B0015</option><option value='B0016'>B0016</option><option value='B0017'>B0017</option><option value='B0018'>B0018</option><option value='B0019'>B0019</option><option value='B0020'>B0020</option>
</select>
<input type="submit" name="submit" value="Remove Book" style="width:auto;">
</form>
Thank you for your help in advance!
Try to print and see whether you are getting the selected Book ID.
Whenever you get a prob in query print and see.
add this line
print "DELETE FROM books WHERE book_id=$books";
before
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
I think you did not receive the Book Id in proper format.
Change the line
echo "<option value=\"".$book_id."\">".$book_id."</option>";
as
echo "<option value='".$book_id."'>".$book_id."</option>";
And also use single quotes to encapsulate a value.
Change
$result=mysql_query("DELETE FROM books WHERE book_id=$books");
to
$result=mysql_query("DELETE FROM books WHERE book_id='".$books."'");
IF your book_id field is varchar or text, you should add quotes between $books
...WHERE book_id='$books'
Related
I'm trying to make the user choose from a checkbox then display the right list to him.
here is my code:
qualification: <select name="qualification">
<option value="ET">ET</option>
<option value="TM">TM</option>
</select><br>
current registration: <input type="checkbox" name="classRegular" value="RegularClass">Regular Class<br>
<input type="checkbox" name="classTaahdoh" value="Taahdoh">Taahdoh<br>
<?php
$selectedQualification = $_POST['qualification']; // Storing Selected Value In Variable
if(isset($_POST['classRegular'])){
if ( $selectedQualification == "ET") {
echo 'Class: <select name="regularClass">';
$sql = "SELECT idClass FROM Class Where category = 'ET' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//output data of each row in dropdown list
while($row = $result->fetch_assoc()) {
echo "<option value='{".$d['idClass']."}'>".$d['idClass']."</option>";
}
} else {
echo '0 results';
}
?>
It doesn't show the list after the user check the type of class,
is it because I check with 'POST' ?
What other options I can do?
Any help please?
If you want to display list after the user checks the type of class, please remove
if(isset($_POST['classRegular'])) {
if block from code. Then list of answers will be displayed every time.
1.There is no way to send the result to the page.Unless you use a submit button or ajax
2.There is no connection to the database.
So add something like this code :
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'yourpassword');
define('DB_NAME', 'yourwebsite');
/* Attempt to connect to MySQL database */
try{
$pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
Also, used prepared statements.Yes you aren't directly accepting user inpuit but a malicious user could still inspect the page and change the value of the option to a dangerous one
i am having trouble in deleteing values from my database using php can someone help me plsss this is for my project
this is where i get the value
<select name="fname" id='mySelect' value='Foodname'>
and this is what i want to do after i submit it
if(isset($_POST['submit']))
{
$food = $_POST['fname'];
echo $food;
if($food=='')
{
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
sqldel="DELETE FROM menu WHERE food = $food;";
}
}
This is how your complete code should be look like. Hope it helps!!!
<form name="" method="post" action="">
<select name="fname" id='mySelect' value='Foodname'>
<option value="">select</option>
<option value="option1">option1</option>
<option value="print server, printer">print server, printer</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
//Check if Form is submitted
if(isset($_POST['submit']))
{
//Store submitted value in variable
$food = $_POST['fname'];
echo $food;
//Check if the submitted value is blank or not
if($food=='')
{
//User submitted blank value - so throw an error
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
/*user selected a valid value in drop down so we are in else part*/
//This is your database configuration settings
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "yourDBName";
// Create connection - here you are doing database connection
$conn = new mysqli($servername, $username, $password, $dbname);
/* Check connection - If you database configuration settings are wrong it will throw an error and stop there itself and wont execute your further code*/
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/*Now Check if record exists in db for the selected value. If record exists in database than only we can delete record.*/
$sql = "SELECT id FROM menu WHERE food = '".$food."'";
$result = $conn->query($sql);
/*check if select query return a row greater than 0, implies record exists in table */
if ($result->num_rows > 0) {
/*Record exists in database so - sql to delete a record*/
$delete_sql = "DELETE FROM menu WHERE food = '".$food."' ";
/*this will execute the delete query, if it return true we will show success alert else throw an error*/
if ($conn->query($delete_sql) === TRUE) {
echo"<script>alert('Record deleted successfully')</script>";
} else {
echo "Error deleting record: " . $conn->error;
}
} else {
echo"<script>alert('No record found for the seleted item')</script>";
}
//Close database connection
$conn->close();
}
}
?>
just remove ; after query and put single quote around variable $food
sqldel="DELETE FROM menu WHERE food = $food;";
shoulb be
sqldel="DELETE FROM menu WHERE food = '$food'";
Here is a fix for your query:
$sqldel = "DELETE FROM menu WHERE food = '".$food."'";
You need to put quotes around $food.
$sqldel="DELETE FROM menu WHERE food = '$food';";
I want to insert a data into a mysql database, but I need to put some constrains over that insertion. And my code is not working for me.
Basically I have selected "departments" from the mysql db using html select tag and show that in dropdown. And now I want to insert subject and subject code in front of that row which is selected in the drop down. But the problem is my code is not working and show me error please help and checkout code.
This is code for inserting data from mysql database. It work's fine.
<code>
<select class="form-control" name="department">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('sims',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `sims-reg-department`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[dept-id];'?>"><?php echo $row["dept-name"];?></option>
<?php }
?>
</select>
</code>
This section is showing me errors:
<code>
<?php
if(isset($_POST['submit'])){
$dptname = $_POST["department"] or
$coursename = $_POST["course-name"] and
$coursecode = $_POST["course-code"];
if($coursename=="" or $coursecode=="" )
{
echo "Please fill all the fields before hit submitting button";
return true;
}
else
{
$q = "INSERT INTO `sims-reg-department`(`course-name`,`course-code`)VALUES ('$coursename','$coursecode') where '$dptname' LIKE `dept-name`";
}
$res = mysql_query($q) or die(mysql_error());
mysql_close($con);
}
?>
</code>
I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>
The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax