I have a Reports page with 2 tables, one show items in stock the other shows Items sold.
I made a delete option for them which provides a button at the right end side of the table to delete rows out of my table.
The Issue that I am having is that the Code works perfectly for the 1st table but for the second table, the code will execute but the data does not get deleted from the DB.
I think what is happening is that due to me using the same Code to delete from both tables, that only 1 works. ( I think I am not sure)
After looking at it for a while trying to find potential errors I made and trying to see what else might be the issue, I decided to ask u for help!
Here the code:
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM BCD WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID, Categorie, SerieNummer, MacAdress, ProductCode, Prijs, RekNummer, PaletNummer, Hoeveelheid, Aantekeningen FROM BCD";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Categorie</th>";
echo "<th>SerieNummer</th>";
echo "<th>MacAdress</th>";
echo "<th>ProductCode</th>";
echo "<th>Prijs</th>";
echo "<th>RekNummer</th>";
echo "<th>PaletNummer</th>";
echo "<th>Hoeveelheid</th>";
echo "<th>Aantekeningen</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Categorie}</td>";
echo "<td>{$SerieNummer}</td>";
echo "<td>{$MacAdress}</td>";
echo "<td>{$ProductCode}</td>";
echo "<td>{$Prijs}</td>";
echo "<td>{$RekNummer}</td>";
echo "<td>{$PaletNummer}</td>";
echo "<td>{$Hoeveelheid}</td>";
echo "<td>{$Aantekeningen}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb2'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM CDE WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Klant</th>";
echo "<th>Categorie1</th>";
echo "<th>SerieNummer1</th>";
echo "<th>MacAdress1</th>";
echo "<th>ProductCode1</th>";
echo "<th>Prijs1</th>";
echo "<th>Hoeveelheid1</th>";
echo "<th>Aantekeningen1</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Klant}</td>";
echo "<td>{$Categorie1}</td>";
echo "<td>{$SerieNummer1}</td>";
echo "<td>{$MacAdress1}</td>";
echo "<td>{$ProductCode1}</td>";
echo "<td>{$Prijs1}</td>";
echo "<td>{$Hoeveelheid1}</td>";
echo "<td>{$Aantekeningen1}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID2} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
So in short: 1st Table: everything works, all data gets deleted
2nd Table: Appears to be working but after confirming the Delete, the data is still there and didn't get removed from my DB.
The Code for Table 2 is exactly the same as the code for Table 1 exepct for the Names of DB and Table etc.
I am hoping you can go over my code see if you notice anything that might be causing this.
Maybe if u agree with what I was thinking, that the same code will not work for both tables on the same page, that you can give an example or a link to how I can tackle this issue?
Sorry for the Long code!
Thank you in advanced!
You shouldn't mix the delete's because you might have an instance when one id be the same as the other, so you'll delete the wrong thing. But I don't believe that is your primary problem:
Your select is
SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE
But your delete is:
DELETE FROM CDE WHERE id = ?";
You're delete should probably be:
DELETE FROM CDE WHERE ID2 = ?";
To Prevent Deleting the wrong thing:
The easiest thing to do here, is change you're delete user JavaScript to accept an action parameter and specify which delete you want to perform, because both delete attempts are running right now.
JavaScript
You don't need the JavaScript twice on the same page. Just have it one time in your HEAD or right before the end of the body.
<script type='text/javascript'>
function delete_user( action, id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=' + action + '&id=' + id;
}
}
</script>
Checking Action
if ($action=='delete_BCD') {
// or
if ($action=='delete_CDE') {
Rendering Rows
echo "<a href='#' onclick='delete_user( \"delete_BCD\", {$ID2} );'>Delete</a>";
// or
echo "<a href='#' onclick='delete_user( \"delete_CDE\", {$ID2} );'>Delete</a>";
Related
I have two PHP files: itemTransaction.php and recordItemTransaction.php. I can select which row I would like to record a transaction for from a table in itemTransaction, and it links to the correct row in the database in recordItemTransaction.php, leading to a form allowing me to edit the itemQuantity. I have a form that has a hidden ID field and a textbox for the user to enter in an updated itemQuantity, which will be submitted to the database upon submission. I would like to display the current itemQuantity to the user, so when they edit the itemQuantity, they know what the current quantity is before they edit it and record the transaction.
My issue is that in recordItemTransaction.php, I cannot figure out how to pull in both the values for ID and itemQuantity in the same file.
This links to recordItemTransaction.php. Since I am referencing ID here, I can retrieve it in the next file. But I cannot retrieve itemQuantity along with the ID. Only one or the other. So, when I switch it to...
...I can retrieve the itemQuantity value in the textbox, but when I submit the form, it cannot tell which row to update.
itemTransaction.php
$query = "SELECT * FROM `Items` WHERE `isActive` = 'Active'";
$result = mysqli_query($con, $query);
echo "<h1>Record Transaction | Items</h1>";
echo "<a href='../inventoryIndex.php'><button class='button'>Back</button></a>";
//Display Data
echo "<table class='applyFont' cellspacing='0' cellpadding='0'>";
echo "<tr>";
echo "<th></th>";
echo "<th>ITEM</th>";
echo "<th>COST</th>";
echo "<th>RECORD TRANSACTION</th>";
echo "</tr>";
while($row=mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td align='center' width='9%'><img src='/InventoryManager/InventoryManagerImages/Items/{$row['itemImage']}' width='115' height='125' style='display:block'></td>";
echo "<td align='center' width='30%'>{$row['description']}</td>";
echo "<td align='center' width='30%'>$ {$row['unitCost']}</td>";
echo "<td align='center'><a href='recordItemTransaction.php?ID={$row['ID']}'><img src='/InventoryManager/InventoryManagerImages/Icons/couple-of-arrows-changing-places.png' title='Record an update to inventory'></td>";
echo "</tr>";
}
?>
</body>
</html>
recordItemTransaction.php
>
>
<?php
if(isset($_POST['updateQuantity'])) {
//Connect to DB
$hostname = "******";
$username = "******";
$password = "******";
$dbName = "******";
$con = mysqli_connect($hostname, $username, $password, $dbName);
//Get Value From User
$itemQuantity = $_POST["itemQuantity"];
$ID = $_POST["ID"];
//Query to Update Data
$query = "UPDATE `Items` SET `itemQuantity`='$itemQuantity' WHERE ID='$ID'";
$result = mysqli_query($con, $query);
//Check if Query Was Successful
if($result) {
echo "<p style=font-family:'Roboto Condensed', sans-serif>Item quantity has been updated</p>";
} else {;
echo "<p style=font-family:'Roboto Condensed', sans-serif>Error updating the quantity of the item.</p>" . mysqli_error();
}
//Disconnect From DB
mysqli_close($con);
}
?>
<body>
</body>
</html>
I'm having an issue where I have a drop down list which has owner's last name and once I select it and press delete button, it should remove the owners name from the drop down along with any associated owner information and boat information in mySQL database. I have written the #sql query to perform the delete function but doesn't seem to delete it.
Also how can I print out the tables (owner table and MarinaSlip table, these are the names in the mySQL database) once user click delete button. I want it to display both tables underneath in the same page.
deletedowner.php:
<?php #index.php for Assignment 10
$page_title = 'Assignment 10 for Marina Database';
include('header.html');
require('dbConn.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = $_POST['OwnerID'];
try
{
$sql = "DELETE m, o
FROM Owner AS o
LEFT JOIN MarinaSlip AS m
ON o.OwnerNum = m.OwnerNum
WHERE o.OwnerNum = :ownerId";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':ownerId' => $id));
//include('DeletedUpdatedList.php'); when I put uncomment this line, it shows table but the delete button disappears
} // end try
catch (PDOException $e)
{
echo 'Error: '.$e->getMessage();
} //end catch
} //end if server
echo '<center>';
echo '<h3> Select the owners last name from drop down list to delete owner and their boats.</h3>';
$sql = "select OwnerNum, LastName from Owner"; //prints sql query
echo '<form action="Assignment10deleteowner.php" method="POST">';
echo "<select name='OwnerID' id=OwnerID'>";
foreach($conn->query($sql) as $row)
{
echo '<option value = "';
echo $row['OwnerNum'];
echo '"> ';
echo $row['LastName'];
echo '</option>';
} // end foreach
echo '</select>';
echo '<br><input type="submit" name="submit" value="Delete"> <br>';
echo '</form>'; //end form
// now to check if the delete button has been clicked
include('footer.html');
?>
DeletedUpdatedList.php
<?php #index.php for Assignment 10
$page_title = 'Assignment 10 for AlexaMara Marina Database';
echo '<h2> Updated list of Owners and MarinaSlip:</h2>';
$stmt = $conn->prepare("select * from Owner"); //prepare statment to print all of the owners
$stmt->execute(); //excute the sql query
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt = $conn->prepare("select * from MarinaSlip"); //prepare statment to print all of the owners
$stmt->execute(); //excute the sql query
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "<table style='border: solid 1px black;'>"; //make table to display column headers
echo "<tr><th>OwnerNum</th><th>LastName</th><th>FirstName</th><th>Address</th><th>City</th><th>State</th><th>Zip</th></tr>";
class TableRows extends RecursiveIteratorIterator
{
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v)
{
echo $v;
}
$conn = null;
echo "</table>"; //end table
//$sql = 'select BoatName, m.MarinaNum, SlipID from MarinaSlip s, Marina m where s.MarinaNum //= m.MarinaNum';
//echo '<form action="Assignment9.php" method="POST">';
//echo '</form>';
?>
[only prints 1 table and now formatting is messed up. The drop down and delete button should be first and then should display both tables][1]
Any help to do this would be much appreciated, thanks in advance
For numerous reasons, including protection from SQL injection, you should be using a prepared statement for your DELETE statement. You also must actually execute the statement for it to have any effect.
Here's the relevant portion of your code, modified to operate correctly:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = $_POST['OwnerID'];
try
{
$sql = "DELETE m, o
FROM Owner AS o
LEFT JOIN MarinaSlip AS m
ON o.OwnerNum = m.OwnerNum
WHERE o.OwnerNum = :ownerId";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':ownerId' => $id));
} // end try
catch (PDOException $e)
{
echo 'Error: '.$e->getMessage();
} //end catch
} //end if server
By using a prepared statement, you gain automagic escaping, quoting and type-matching of variables.
Also, don't overcomplicate things. To get your tables to display,
$stmt = $conn->query('SELECT * FROM Owner');
echo '<table>';
while ($row = $stmt->fetch(PDO::FETCH_NUM))
{
echo '<tr>';
foreach ($row as $value)
{
echo "<td>{$value}</td>";
}
echo '</tr>';
}
echo '</table>';
should suffice. Change the query string for the MarinaSlip table as appropriate. Once that's working, then you can play with fancy formatting.
Execute the DELETE query to perform the deletion.
try
{
$sqlDel = "DELETE o, m
FROM Owner o
left join MarinaSlip m
on o.OwnerNum = m.OwnerNum
WHERE o.OwnerNum = '{$id}';" ;
$conn->query($sqlDel);
} // end try
catch (PDOException $e)
{
echo 'Error: '.$e->getMessage();
} //end catch
You can use inner join if both table will have data always
I am using this code which allows me to see my DB records in a table and in this table there is an option to delete or edit the records.
Only I get this error message and I can't figure out what I am doing wrong.
The error message:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\Inventaris++\NinjaCodeDelete.php on line 32
The code:
<?php
include'Connect2db3.php';
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM BCD WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
$query = "SELECT ID, Categorie, SerieNummer, MacAdress, ProductCode, Prijs, RekNummer, PaletNummer, Hoeveelheid, Aantekeningen FROM BCD";
$stmt = $conn->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
echo "<a href='reports.php'>View Reports</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
echo "<tr>";
echo "<th>Categorie</th>";
echo "<th>SerieNummer</th>";
echo "<th>MacAdress</th>";
echo "<th>ProductCode</th>";
echo "<th>Prijs</th>";
echo "<th>RekNummer</th>";
echo "<th>PaletNummer</th>";
echo "<th>Hoeveelheid</th>";
echo "<th>Aantekeningen</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$Categorie}</td>";
echo "<td>{$SerieNummer}</td>";
echo "<td>{$MacAdress}</td>";
echo "<td>{$ProductCode}</td>";
echo "<td>{$Prijs}</td>";
echo "<td>{$RekNummer}</td>";
echo "<td>{$PaletNummer}</td>";
echo "<td>{$Hoeveelheid}</td>";
echo "<td>{$Aantekeningen}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){
window.location = 'NinjaCodeDelete.php?action=delete&id=' + id;
}
}
</script>
I also want to say that I am not an advanced programmer I found this code online, where it seemed to be working for the other people who have used it.
I have some experience with Mysql and php but not with PDO.
I hope u can help me!
thank you in advanced.
What is inside your " include'Connect2db3.php'; "?
And with this I'm refering to connect2db3.php and is this file inside the right folder?
Your connection could look like this:
<?php
$config['conn'] = array(
'host' => 'yourHostName',
'username' => 'yourUserName',
'password' => 'yourPassword',
'dbname' => 'yourDBName'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
?>
I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
I have problems with deleting a record from the screen using MSQLI.
Here you can see the code i'm using.
<?php
include_once("assets/classes/connection.php");
include_once("assets/classes/article.class.php");
while($test = $allArticles->fetch_assoc())
{
if($test['titel']=="")
{
echo "<div class='zonderfoto'>";
echo "<h5>"."geen titel hier, aparte opmaak geslaagd" . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<input type='submit' name='verwijderee' value='verwijder'>";
echo "</div>";
}
else
{
echo "<div class='metfoto'>";
echo "<h1>".$test['titel'] . "<br /></h1>";
echo "<p>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' name='verwijder' value='verwijder'>";
echo "</form>";
echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
}
$vArticle = new Article;
$vArticle -> Key = $test['id'];
if (isset($_POST['verwijder']))
{
$vArticle -> deleteArticle();
echo ("shit");
}
?>
I'm using a while function to print all the DB records on the screen. The if function is just a function to give some design with css so nothing more. With the delete button i want to delete the record from the screen. With the $test['id'] variabele you receive the ID of the record in the DB
Ok here is my code from the class.
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
if (!$mysqli -> query($sSql))
{
throw new Exception("Something went wrong");
}
}
EDIT
There is something wrong with the key, i replaced the where statement with title ="", so i deleted one title in the database, and when i click on delete then, he delete one row, but this is not happening at runtime. so i click delete, one row deleted, BUT the content only dissapear with a page refresh. The solution is using ajax?
public function deleteArticle()
{
include("connection.php");
$sSql = "DELETE FROM tblArticles WHERE id = '".$this->m_sKey."'";
$mysqli->query($sSql);
$aff_rows = $mysqli->affected_rows;
if ($aff_rows){
print("Affected rows (DELETE): %d\n", $aff_rows);
}
else{
print("Nothong Happend ?");
if ($err = $mysqli->error){
print("Error: %s\n", $err);
}
}
}