delete mysql row by retrieving id PHP foreach - php

I've created a foreach statement that echos out some stuff about all users registered, how do I make a button that deletes that user from the row? I've tried this:
$query = "
SELECT id
, name
, bname
, email
, address
, agent
, status
, notes
FROM prospects
";
try {
$stmt = $db->prepare($query);
$stmt ->execute();
}
catch(PDOException $ex) {
die("Failed to run query. Tell the website owner!");
}
$rows = $stmt->fetchAll();
foreach($rows as $row) {
echo "<tbody>
<th>".$row['name']."</th>";
echo "BLAH BLAH BLAH!";
echo "<form method='post'><th><button type='submit' name='delete' class='btn btn-white btn-round btn-just-icon'>
<i class='material-icons'>remove_circle_outline</i>
<div class='ripple-container'></div>
</button></th></tbody></form>";
} $id = $db->prepare("SELECT id FROM example");
$id->execute();
$result = $id->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['delete'])) {
try {
$sql = "DELETE FROM example WHERE id='".$result."'";
$db->exec($sql);
}
catch(PDOException $e) {
echo $sql . "<br />". $e->getMessage();
}
}
It returns this error:
Notice: Array to string conversion....
I know this is because I've grabbed the id and there is an array of ids that I've grabbed from the database? So how do I do delete a specific row when i click on the button?

You have to specify which element in array holds the id value.
Try:
$sql = "DELETE FROM example WHERE id='".$result['id']."'";

Related

PHP PDO How to Get ID Out of Database By Using URL

I've searched a bunch for this question but I'm not finding an answser. I'm new to PHP, creating a simple CRUD app using PDO. But I have an empty id from my SQL query. I'm trying to use the $_GET super global to pull the id from the database out of the URL so that I can retrieve the proper data to populate my form value="<?php echo $row['item'] ?>". But since the id is blank, I just get an undefined index error. Any help would be greatly appreciated. This is what I have tried.
if(isset($_GET['id'])){
$item = $_POST['item'];
$itemPrice = $_POST['item_price'];
try {
$sql = "UPDATE grocery_list SET item = :item, item_price = :item_price WHERE id = :id";
$statement = $pdo->prepare($sql);
$statement->execute(array(":item" => $item, ":item_price" => $itemPrice));
} catch (Exception $ex) {
echo "An error occurred " . $ex->getMessage();
}
} else {
echo "id is empty";
}
Try this ,
if(isset($_GET['id'])){
$id = $_GET['id'];
$item = $_POST['item'];
$itemPrice = $_POST['item_price'];
try {
$sql = "UPDATE grocery_list SET item = :item, item_price = :item_price WHERE id = :id";
$statement = $pdo->prepare($sql);
$statement->execute(array(":item" => $item, ":item_price" => $itemPrice,":id" => $id));
} catch (Exception $ex) {
echo "An error occurred " . $ex->getMessage();
}
} else {
echo "id is empty";
}

Delete the record if its exist , else insert

I have a click favorite star , i want to check in data base if the record is exist it will delete the record , if it not exist it will insert the record ,what is the problem the record not inserted
<?php
include "config.php";
header('Content-Type: application/json');
$landmarkid = $_GET['landmarkid'];
$userid = $_GET['userid'];
try {
$query = mysqli_query($con,"SELECT * from favourite WHERE userid =$userid AND L_ID = $landmarkid");
if(mysqli_num_rows($query) > 0)
{
$q1 = mysqli_query($con,"DELETE from favourite WHERE userid =$userid AND L_ID = $landmarkid");
if($q1){
echo '{"Deleted":"true"}';
}
else {
echo '{"Deleted":"false"}';
}
}
else {
$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( $userid, $landmarkid) ");
if($q2){
echo '{"inserted":"true"}';
}
else {
echo '{"inserted":"false"}';
}
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
Try to add single quotation marks to your insert statement and see if it works. Change this statement;
$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( $userid, $landmarkid) ");
To this;
$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( '$userid', '$landmarkid') ");
Let me know if it helps or if you find a problem.
I have rewritten your code below.
Some points:
Your code was vulerable to SQL injection so assuming id is a numeric value I forced the input vars ($userid and $landmarkid) to be integers using (int) casting.
Your first checking query can return a COUNT value, it's better than returning a * and then you can check a specific value for your if statements, $result['numb'].
I have properly escaped your php variables in the SQL, but you really should be trying to use Prepared Statements for this.
I dont think you need the try{} catch {} here as your current code will never throw exceptions (as far as I'm aware)
Add a LIMIT to your delete statements so you can never delete more than an intended number of row. This acts as a failsafe so you don't inadvertantly manage to delete the whole table.
<?php
include "config.php";
header('Content-Type: application/json');
$landmarkid = (int)$_GET['landmarkid'];
$userid = (int)$_GET['userid'];
try {
$query = mysqli_query($con,"SELECT COUNT(*) as numb FROM
favourite WHERE userid = ".$userid." AND
L_ID = ".$landmarkid);
$result = mysqli_fetch_aray($query);
if($result['numb'] > 0)
{
$q1 = mysqli_query($con,"DELETE FROM favourite
WHERE userid = ".$userid." AND L_ID = ".$landmarkid."
LIMIT 1");
print "deleted";
}
else {
$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID)
VALUES ( ".$userid", ".$landmarkid.") ");
print "inserted";
}
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>

delete query doesn't work

I made a delete query. The delete query is used to delete posts made by the admin but if I click on the the delete button I go to a screen with object not found.
I will show the delete query:
include '../db/db.php';
$id = $_GET['0'];
$query = "DELETE FROM pages WHERE paginaNummer = :id";
$stmt = $dbcon->prepare($query);
$stmt->execute(array(':id' => $id));
$row=$stmt->fetch();
header("Location: http://127.0.0.1/cmsFenB/index.php");
Here is the db connection:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=register', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
?>
And here is the link that referrers to this script:
echo " <a class='delete' href='fucntions/admin/delete.php?id=" . $pageNumber . " '>Delete</a>";
I hope you can help me out with this problem.
You have a typo in the referrer link. It should look like this:
echo " <a class='delete' href='functions/admin/delete.php?id=" . $pageNumber . " '>Delete</a>";
$id=$_GET['0']; ? I think you meant something like $_GET['id']
$id=$_GET['id'];
$query = "DELETE FROM pages WHERE paginaNummer = :id";
$stmt = $db->prepare($query);
$stmt->execute(array(':id' => $id));

PHP - Search Using Form and Return Back Records

I am working in PHP/HTML/SQLITE3. I have a database that consist of several tables, one of the tables is called Item, which contains an itemID, name of item, and so forth. So my search takes the user input of the itemID and what I am suppose to return back is everything associated with that itemID.
I have tested out my search and it does return back the itemID, however, I am having a bit of trouble figuring out how to return back everything related to the itemID. Down below are my search form and what I have for a seperate file which contains the query.
<form method="POST" action="action.php">
<input name="search" type="text" size="20" maxlength="10"/>
<input type="submit" value="Search"/>
</form>
-----
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
$result = $db->query($query);
if (empty($_POST['search'])){
echo "<strong>You didn't fill in anything!</strong>";
}
else {
echo $itemID;
}
$db->commit();
}
$db = null;
?>
Edit Code (Addition of attempt at fetchall):
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach($result as $entry) {
echo 'ItemID: ' . $entry['itemID'] . ' Item Name' . $entry['name'];
}
if (empty($_POST['search'])){
echo "<strong>Esteemed customer did not fill in a
itemID number, please search again. </strong>";
}
$db->commit();
}
2nd Attempt:
<?php
$dbname = "mydatabase.db";
try {
// Establish connection to "mydatabase.db"
$db = new PDO("sqlite:" . $dbname);
// Set error handling so that errors throw an exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Enable foreign key constraints on the database
$db->exec("PRAGMA foreign_keys = ON;");
} catch (PDOException $e) {
echo "SQLite connection failed: " . $e->getMessage();
exit();
}
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$sth = $db->prepare("SELECT * FROM Item WHERE itemID = '$itemID'");
#$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
#if (empty($_POST['search'])){
#echo "<strong>Esteemed customer did not fill in a
#itemID number, please search again. </strong>";
}
}
?>
Any input would be greatly appreciated.
You should concatenate the itemid to the query
$query = "SELECT * FROM Item WHERE itemID = '" . $itemID . "';";

Create foreach for a value that exists twice

I have the following statement which SELECTs ProductName and Quantity from the orderDetails table. See below:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
$_POST['ProductName'] = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
If $_POST['ProductName']['ProductName'] exists more than once how can I create a foreach loop based on that?
What I have tried so far...
foreach($_POST['ProductName']['ProductName']) {
}
This did not work...
What have I done wrong?
Complete Code:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
array_push($_POST["ProductName"], $stmt->fetch(PDO::FETCH_ASSOC));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['ProductName']['ProductName'];
// echo $_POST['ProductName']['Quantity'];
try {
$stmt1 = $conn->prepare("SELECT Stock FROM products WHERE ProductName = :ProductName");
$stmt1->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt1->execute();
$_POST['Stock'] = $stmt1->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['Stock']['Stock'];
$_POST['DEDUCT'] = $_POST['Stock']['Stock'] - $_POST['ProductName']['Quantity'];
try {
$stmt2 = $conn->prepare("UPDATE products SET Stock = :Stock WHERE ProductName = :ProductName");
$stmt2->bindParam(':Stock', $_POST['DEDUCT']);
$stmt2->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt2->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You can make a new array called (for example, $rows) which contains all of the fetched data using the function fetchAll() (fetch() only retrieves the next one row).
The most straightforward way to do this is as follows:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
//Add all returned values to an array called "$rows"
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then if you want to access that data later you can do:
foreach($rows as $row){
var_dump($row); //Show the data in the row to double-check
}
You can create array using foreach like this :
$newval_arr = array();
foreach($_POST['ProductName']['ProductName'] as $key=>$value) {
if(!in_array($value,$newval_arr) || empty($newval_arr))
{
$newval_arr[] = $value;
}
}
Then after you can use $newval_arr in foreach
foreach($newval_arr as $key=>$value)
{
//Your code herer
}

Categories