John
John

Reputation: 115

Deleting database row via PHP

I've looked through the "recommendations" based on the title I placed this as and the topics either weren't answered or didn't relate to my situation (from what I could see).

I've got a PHP HTML page that calls information from a database and inputs it into a table. I've got a a tag ready for a delete function but I just can't seem to get it right. I was hoping someone here would be able to help me out.

These are all the relevant pages.

connection.php

<?php
    try{
        $handler = new PDO('mysql:host=127.0.0.1;dbname=data', 'root', 'root');
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
        echo 'ERROR: ' . $e->getMessage();
    }
?>

location1.php

<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
    <h1 align="center">Location 1</h1>
    <table align="center" border="1" height="10%" width="80%">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Desc</th>
            <th>Location</th>
            <th></th>
    </tr>
    <?php while($row = $query->fetch()){ '<tr>
        <td align="center">';echo $row[''],'</td>
        <td align="center">';echo $row['id'],'</td>
        <td align="center">';echo $row['name'],'</td>
        <td align="center">';echo $row['desc'],'</td>
        <td align="center">';echo $row['location'],'</td>
        <td align="center"><a href="connection.php?id='.$row['id'].'">Delete</a></td>
    </tr>';}  ?>
</table>

When I try to keep the mysql delete call in the first php section in location1 it breaks the page, I'm pretty sure it has something to do with the fact that I am assigning 2 calls to 1 function but I other than making a brand new page jsut for a single delete call I don't know what else to do

Upvotes: 0

Views: 45

Answers (2)

admiralchip
admiralchip

Reputation: 145

I'm not so familiar with PDO but from what I see this line has a problem:

$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');

It should be this I think:

$delete = $handler->query('DELETE FROM subsordered WHERE id = :id');

Have a look at the example here: http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/

Upvotes: 0

Mindastic
Mindastic

Reputation: 4121

Try:

<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
if (isset($_GET["id"])) {
  $delete = $handler->exec('DELETE FROM subsordered WHERE id = \'' . $_GET["id"] . '\'');
}

?>

This should work. Anyway, i would consider changing the code in order to prevent SQL injection (Check this)

Upvotes: 2

Related Questions