delete goods from table using mysql php - php

I have a problem where i cant delete a row in the table i have. When i select something and click on delete, nothing happends its just refresh the page and i can select again, but the row is still there. I use the code on this page: index.php?page=Delete
Below is my code:
try{
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
$action = empty($_GET['']) ? "" : $_GET[''];
if ($action == "") # No action specified so show the home page
{
try{
$sql = "select id, name, price from goods";
$STH = $DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo "<form method='post' >";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Price</th><th>Select</th></tr>";
while ($row = $STH->fetch())
{
echo "<tr><td><br>{$row["name"]} {$row["price"]} </td>";
echo "<td>";
echo "<input type='radio' value='{$row["id"]}' name='id2edit'>";
echo "</td></tr>";
}
echo "</table>";
echo "<br>";
echo "<input type='submit' value='Delete selected product' name='button'>";
echo "</form>";
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
else if ($action == "action='index.php?page=Delete'")
{
$id2edit = empty($_POST["id2edit"]) ? "" : $_POST["id2edit"];
if ($id2edit == "")
{
$m = "No goods selected! To return to the home ";
$m .= "screen click <a href='delcust.php'>here.</a>";
show_message($m);
}
else
{
try{
$STH = $DBH->prepare('delete from goods where id = :id');
$STH->bindParam(':id', $id2edit);
$STH->execute();
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
}
I have come further now but still the value in teh table is not deleted: here is the code i have right now:
try{
# a DB Handler to manage the database connection
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
$action = empty($_GET['action']) ? "" : $_GET['action'];
if($action == "Delete"){
try{
$sql = "select id, name, price from goods";
$STH = $DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo "<form method='post' action='delcust.php?action=delete_record'>";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Price</th><th>Select</th></tr>";
while ($row = $STH->fetch())
{
echo "<tr><td><br>{$row["name"]} </td> <td> {$row["price"]} </td>";
echo "<td>";
echo "<input type='radio' value='{$row["id"]}' name='id2edit'>";
echo "</td></tr>";
}
echo "</table>";
echo "<br>";
echo "<input type='submit' value='Delete selected product' name='button'>";
echo "</form>";
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
else if ($action == "delete_record")
{
include("header.php");
include("nav.php");
include("aside.php");
$id2edit = empty($_POST["id2edit"]) ? "" : $_POST["id2edit"];
if ($id2edit == "")
{
$m = "No goods selected so far! Please select";
echo("$m");
}
else {
try{
$STH = $DBH->prepare('delete from goods where id = :id');
$STH->bindParam(':id', $id2edit);
$STH->execute();
echo "Goods with ID $id2edit deleted. :id To return to the home ";
echo "screen click <a href='index.php'>here.</a>";
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
include("footer.php");
}
}
?>
Problem solved:
$sql = "delete from goods where id = :id";
$STH = $DBH->prepare($sql);
now it works do delete values.

if ($action == "") is always true as $_GET[''] is always undefined(and return NULL) and empty($_GET['']) is always true.
Try below code:
try {
if ($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
} catch (PDOException $e) {
echo '<b>PDOException: </b>', $e->getMessage();
die();
}
$action = isset($_GET['page']) ? $_GET['page'] : '' ; // MODIFIED
if ($action == "Delete") { // MODIFIED
$id2edit = empty($_POST["id2edit"]) ? "" : $_POST["id2edit"];
if ($id2edit == "") {
$m = "No goods selected! To return to the home ";
$m .= "screen click <a href='delcust.php'>here.</a>";
show_message($m);
} else {
try {
$STH = $DBH->prepare('delete from goods where id = :id');
$STH->bindParam(':id', $id2edit);
$STH->execute();
} catch (PDOException $e) {
echo '<b>PDOException: </b>', $e->getMessage();
die();
}
}
}
try {
$sql = "select id, name, price from goods";
$STH = $DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo "<form method='post' >";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Price</th><th>Select</th></tr>";
while ($row = $STH->fetch()) {
echo "<tr><td><br>{$row["name"]} {$row["price"]} </td>";
echo "<td>";
echo "<input type='radio' value='{$row["id"]}' name='id2edit'>";
echo "</td></tr>";
}
echo "</table>";
echo "<br>";
echo "<input type='submit' value='Delete selected product' name='button'>";
echo "</form>";
$DBH = null;
} catch (PDOException $e) {
echo '<b>PDOException: </b>', $e->getMessage();
die();
}

Related

Cannot update value in PHP

I have a problem with updating value with PHP, it can get the data that I input but it cannot update it and render it to the read page.
<?php
require_once("session.php");
require_once("included_functions.php");
require_once("database.php");
new_header("VinceT");
$mysqli = Database::dbConnect();
$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (($output = message()) !== null) {
echo $output;
}
echo "<h3>Update A Order</h3>";
echo "<div class='row'>";
echo "<label for='left-label' class='left inline'>";
if (isset($_POST["submit"])) {
$stmt = $mysqli->prepare("UPDATE VTCustomer SET CustomerFName=? WHERE CustomerID=?");
$stmt->execute([$_POST["CustomerFName"],$_POST["CustomerID"]]);
$stmt1 = $mysqli->prepare("UPDATE VTCustomer SET CustomerLName=? WHERE CustomerID=?");
$stmt1->execute([$_POST["CustomerLName"],$_POST["CustomerID"]]);
if($stmt) {
$_SESSION["message"] = $_POST["CustomerFName"]." has been updated";
} else {
$_SESSION["message"] = "Error! Could not update ".$_POST["CustomerFName"];
}
redirect("read.php");
} else {
if (isset($_GET["id"]) && $_GET["id"] !== "") {
$stmt = $mysqli->prepare("SELECT OrderID FROM OrderVinceT WHERE OrderID=?");
$stmt->execute([$_GET["id"]]);
if ($stmt) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h3>Order ".$row["OrderID"]." Information</h3>";
}
echo "<form method='POST' action='update.php'>";
echo "<input type = 'hidden' name = 'OrderID' value = ' ".$row['OrderID']." ' />";
$stmt1 = $mysqli->prepare("SELECT CustomerFName FROM VTCustomer WHERE CustomerID=?");
$stmt1->execute([$_GET["id"]]);
if ($stmt1) {
while ($row1 =$stmt1 -> fetch(PDO::FETCH_ASSOC)) {
echo "<p>Customer First Name: <input type='text' name='CustomerFName' value='".$row1["CustomerFName"]."'></p>";
}
}
$stmt5 = $mysqli->prepare("SELECT CustomerLName FROM VTCustomer NATURAL JOIN OrderVinceT WHERE OrderVinceT.CustomerID=?");
$stmt5->execute([$_GET["id"]]);
if ($stmt5) {
while ($row5 =$stmt5 -> fetch(PDO::FETCH_ASSOC)) {
echo "<p>Customer Last Name: <input type='text' name='CustomerLName' value='".$row5["CustomerLName"]."'></p>";
}
}
echo "<input type='submit' name='submit' value='Update Order' class='tiny round button'/>";
echo "</form>";
echo "<br /><p>&laquo:<a href='read.php'>Back to Main Page</a>";
echo "</label>";
echo "</div>";
} else {
$_SESSION["message"] = "Order could not be found!";
redirect("read.php");
}
}
}
new_footer("VinceT");
Database::dbDisconnect($mysqli);
?>
Do you guys have any idia why I cannot update this? I test queries in the console and it works just fine. The if statement that render out the message still receive the value of the input but it cannot update the database that render out in read.php

Trying to print a table uisng PDO

New to PDO and I have a PDO connection script which I am requiring at the top but this is what I have to try and just display the database that is made of up 4 employees and their birthdays. Whenever I run it, I get nothing. Am I at least in the right ballpark here?
<?php
require "pdoconnect.php";
try{
$stmt = $conn->prepare("SELECT bid, bname, bday FROM birthday");
$stmt->execute();
# setting the fetch mode
$result = $stmt->fetchAll();
if( ! $result){
print('No Records Found');
}
else{
echo "<table border='1' align='center' cellpadding='5px' cellspacing='2px'>";
//while($row = $stmt->fetch())
echo "<tr><th>Bid</th><th>Name</th><th>Birthdaay</th><th colspan='2'></th></tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>";
echo $row['bid'];
echo "</td>";
echo "<td>";
echo $row['bname'];
echo "</td>";
echo "<td>";
echo $row['bday'];
echo "</td>";
}
echo "</table>";
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

Search in a table using full or partial

I have a little problem where i try to search for a product and the user can choose to click on a full search or a partial search. Problem is when the user click on full search and type in something, the whole table is printing out and the word of the product is not (i want instead printing out the product and not the whole table) And with partial search, its just print outs it dont find a match. Below here is my code so far:
// DB configuration //
if (!isset($_POST["searchtype"])) {
echo "<form method='POST'>";
echo "Search for product:<br>";
# using html5 input type search
echo "<input type='text' name='searchtext' size='15' placeholder='search' results='5' autosave='saved-searches'>";
echo "<br><br>";
echo "Full search";
echo"<input type='radio' value='FULL' checked name='searchtype'><br>";
echo "Partial search ";
echo "<input type='radio' name='searchtype' value='PARTIAL'>";
echo "<br><br>";
echo "<input type='submit' value='Search' name='submit'>";
echo "</form>";
}
else {
$searchtext = $_POST["searchtext"]; # Retrieve from the form
$searchtype = $_POST["searchtype"]; # Retrieve from the form
$searchtext_san = sanitize_form_text($searchtext); # Prevents SQL injections!
try{
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
$sql = "select name, price, details from products where name='$searchtext_san'";
if ($searchtype == "FULL"){
$sql .= " = :searchtext_san";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => $searchtext_san));
}
if ($searchtype == "PARTIAL"){
$sql .= " LIKE ':searchtext_san'";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => '%'.$searchtext_san.'%'));
}
$STH->setFetchMode(PDO::FETCH_ASSOC);
$total = $STH->rowCount();
if ($total == 0){
echo "Sorry, no matches found!";
}
if ($total > 0){
while ($row = $STH->fetch()){
echo "{$row["name"]} {$row["price"]} {$row["details"]}<br>";
}
}
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
function sanitize_form_text($t)
{
$t = strip_tags($t);
$t = ereg_replace("[^A-Za-z0-9#._-]", "", $t);
return $t;
}
?>
try this for fulltext search
SELECT * FROM articles WHERE MATCH (title,body)
AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
Full text Search description
for partial search you can us like
SELECT name FROM products WHERE name RLIKE '[yourtext]'

Updating an existing value in php

I'm inserting some values into my database, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result.
$options = '';
$filter=mysql_query("select afnumber from employees WHERE Status='Employed '");
while($row = mysql_fetch_array($filter)) {
$options .="<option >" . $row['afnumber'] . "</option>";
}
$menu="<form id='filter' name='filter' method='post' action=''>
AFNumber : <select name='SelectAF' id='filter' style='color:grey;'>" . $options . "</select>
Added hours: <input type='text' name='AddedHours' style=' padding: 10px;border: solid 2px #c9c9c9; width:50px; height:2px;'>
<input type='submit' name='submit' value='Submit' style='width:80px; height:30px; text-align:center; padding:0px;'>
</form>
<br>
";
/* if(isset($_POST['submit'])){
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
if($addedhours == ""){
$sql="INSERT INTO `editedworkhours` (`AFNumber`,`AddedWH`) VALUES('$selectaf','$addedhours')";
$getResult =mysql_query($sql);
}
else{
$sql2 = "UPDATE editedworkhours SET AddedWH=$addedhours WHERE AFNumber=$selectaf";
$getResult =mysql_query($sql2);
}
}
echo $menu; */
echo '<div class="scrolldiv">';
try {
$conn = new PDO('mysql:host=localhost;dbname=hr', 'root', 'J546');
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$num_rows = $conn->query('SELECT COUNT(*) FROM employees')->fetchColumn();
$pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All'));
echo $pages->display_pages();
echo "<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span>";
$stmt = $conn->prepare("SELECT employees.afnumber,employees.name,employees.dateofemployment,employees.actualpost,employees.department FROM employees WHERE employees.status='Employed' AND (employees.afnumber LIKE '%$search%' OR employees.name LIKE '%$search%') ORDER BY employees.afnumber DESC LIMIT :start,:end");
$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
$ewhtable = "<table class='sortable'><tr><th>AFNumber</th><th>Employee Name</th><th>Years of Service</th><th>Actual Post</th><th>Department</th><th>Added Hours</th></tr>\n";
foreach($result as $row) {
$years=explode("/", $row[2]);
$years[2]=intval(date ('Y')) - $years[2];
$sql="SELECT addedwh FROM editedworkhours WHERE afnumber='$row[0]'";
$var = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result2 = $stmt->fetchAll();
foreach ($result2 AS $row2) {
$var .= $row2['addedwh'] . "\n";
}
$ewhtable .= "<tr><td>$row[0]</td><td>$row[1]</td><td>$years[2]</td><td>$row[3]</td><td>$row[4]</td><td>$var</td></tr>\n";
}
$ewhtable .= "</table>\n";
echo $ewhtable;
exportTable(str_replace("&","",$ewhtable),"EmployeeWorkingHoursTable");
echo $pages->display_pages();
echo "<p class=\"paginate\">Page: $pages->current_page of $pages->num_pages</p>\n";
echo "</div>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
If AddedHours input value has only a space, your comparison if($addedhours == "") will fail.
Always trim the values before comparison.
$addedhours = trim($_POST['AddedHours']);

Populate listbox with data from database

<?php
ini_set("display_errors","on");
$conn = new COM("ADODB.Connection");
try {
$myServer = "WTCPHFILESRV\WTCPHINV";
$myUser = "sa";
$myPass = "P#ssw0rd";
$myDB = "wtcphitinventory";
$connStr = "...conn string...";
$conn->open($connStr);
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql_exp = "select * from dbo.PC";
$rs = $conn->Execute($sql_exp);
echo "<table><tr><th>Desktop Number</th></th></tr>";
while (!$rs->EOF) {
set_time_limit(0);
echo "<td>CP # <br>".$rs->Fields("PC_Number")."</td>";
$rs->MoveNext();
}
echo "</table>";
$rs->Close();
?>
i would like to have a list box instead of just a print of all the data of PC_Number from database. All i could do is to echo it and im having a hard time inserting a select. I would like to have a form method post along with a select(listbox)
Create the list box in the while statement.
echo "<table border='1' cellpadding='1' cellspacing='0' id='rounded-corner'><tr><th>Desktop Number</th></th></tr>";
echo "<tr><td><select name='selectionField'>";
while (!$rs->EOF) {
set_time_limit(0);
echo "<option value=".$rs->Fields('PC_Number')." >".$rs->Fields('PC_Number')."</option>";
$rs->MoveNext();
}
echo "</td></tr></table>";

Categories