user1745033
user1745033

Reputation:

Delete row from database with an image and a value that is a primary key

I got this code to show a table on my webpage. The content of the table is linked with a database. So I get the table from the database in a html table. At the end of each (html) row, I got an image (icon-delete.png). This gets the value of the $row[0] (this is where my PKID is, so it's always a unique number and it's an auto ascend. Now I want to clear the individual row where I click on the icon-delete.png button with PHP code. The row has to be deleted from the database also. This is my code at this moment:

$con = mysql_connect('localhost', 'root', '');
if ($con) {
    mysql_select_db('bieren', $con);
    $result = mysql_query('SELECT * FROM brouwers');
    echo '<form action="" method="post">';
    echo '<table border="0" cellspacing=0>';    
    echo '<tr class="heads">
        <th>brouwernr</th>
        <th>brouwernaam</th>
        <th>adres</th>
        <th>postcode</th>
        <th>gemeente</th>
        <th>omzet</th>
    </tr>';

    $counter = 0;
    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        if($counter % 2 == 0){
            echo '<tr class="even">';
        } else{
            echo '<tr class="oneven">';
        }

        for($i = 0; $i <=6; $i++){
            $counter ++;
            echo '<td>';
            echo $row[$i];
            echo'</td>';
        }

        echo '<td> <input type="image" src="icon-delete.png" name="delete" value ="'.$row[0].'" /> </td>';
        echo '</tr>';
    }   
} else {
    echo 'Connectie niet geslaagd. Reden: ' . mysql_error() . '. Probeer opnieuw.';
}
echo '</table>';
echo '</form>';

if(isset($_POST))
{
    $con = mysql_connect('localhost', 'root', '');

    if ($con) {
        mysql_select_db('bieren', $con);
        $result = mysql_query('DELETE FROM brouwers 
                  WHERE brouwers.brouwernr = "'.$row[0].'"');}
}

One of the last rules of my code says: WHERE brouwers.brouwernr = $row[0] but this is not the correct row to delete. I'll also show an image of what I got now in html so you can understand what it has to do:

The webpage view

Upvotes: 0

Views: 1392

Answers (1)

Sherif
Sherif

Reputation: 11943

I believe the answer to your original question is that you need to use $_POST['delete'] as the id of the row you want deleted, which seems to have been answered well by @vlcekmi3, already.

However, what I do believe I can add some additional value to your original problem, and hopefully persuade you to change your mind about using the old ext/mysql extension (which is now deprecated and has long been discouraged). I've noticed that you stated you do not want to use PDO, right now. What I see wrong with that frame of mind is that now is the perfect time to stop using the old mysql API and start using the newer APIs, such as PDO or MySQLi. Rather than try to give you reason not to use the old API, I'm going to try to provide you with some reasons why you should use the newer APIs, instead.

  1. The API you're currently using (the mysql_* functions) is nearly 15 years old. Most of us don't own cars that old. Do you value your code as much as you value your mode of transportation? The extension was introduced during MySQL version 3.x and has remained backwards compatible with that version of MySQL ever since. Due to this extraneous backwards-compatibility constraint the API has remained lacking in supporting all of your database's newer functionality and much of that functionality is invaluable to modern application development on the web today.
  2. The API no longer receives any maintenance or support from the MySQL community. This means you shouldn't expect anything in this extension to change over the years. That includes bug fixes, potential security patches, and anything that changes in MySQL might break your extension over the years. That's not a good thing (you're putting yourself at risk). Both PDO and MySLQi keep your code safe from these risks and also provided added convenience in that if anything should go wrong (any bugs are found) you can expect the extensions to be fixed promptly.
  3. The newer APIs give you features you can't use in ext/mysql, like:
    • Prepared statements (that offers potentially faster performance in many common situations)
    • Parameterized queries (that helps you avoid common human error like the escaping issue you just experienced here)
    • Asynchronous queries (another performance benefit)
    • Stored procedures (an excellent tool that provides advantages you can't do with regular SQL queries)
    • Multiple query functionality
    • Transaction support (for mission critical applications like financial data)
    • SSL support (for when you have multiple database servers over a network)
    • The ability to run commands that interface with your MySQL server, which you can't do with the old API.
  4. The newer APIs make your code easier to read and work with. You can abstract away your SQL logic much of your computational logic with these APIs and avoid unnecessary complexities that ext/mysql puts in your way.
  5. PDO is a database-agnostic API, which means you only have to learn the same set of functions in PHP once to interface with any of the databases PHP can support. Should you have to work with a new database at any given time in the future you won't have to relearn a new interface. That spares you both time and effort in working on your PHP code.

After having looked at some of those benefits I've listed for you; I challenge you to look at the benefits of not switching now and tell me if they outweigh the benefits of switching. I am more than confident you will not be able to come to that conclusion since I can't even think of a single benefit in postponing your move to the newer APIs any further. This old API promotes poor practices, one of which you just realized today as you were getting your answer and it's not just you that has these poor practices ingrained into their brain from years of using ext/mysql. Even I have realized how many poor habits I've picked up from ext/mysql in the last 8 years or so. But when I really looked at the advantages and the disadvantages (and I've spent the last 2 years doing this) I've come to the conclusion that the pros far outweigh the cons.

As a simple example let's see how much more beautiful, easier to read, and easier to debug your code will be if you were to use PDO.

/* This creates a new PDO object that holds the connection to your database */
$db = new PDO('mysql:dbname=bieren;host=localhost;charset=UTF-8', 'root', '');

/* This puts PDO into Exception Mode making it easier for you to catch errors */
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0); // turn off emulation

/* Create your HTML table */
echo "<table>";

// Look how easy it is to loop over the results
foreach($db->query('SELECT * FROM brouwers', PDO::FETCH_NUM) as $i => $row) {
    echo ($i % 2 ? '<tr class="oneven">' : '<tr class="even">');
    foreach ($row as $column) {
        echo "<td>$column</td>";
    }
    echo "</tr>\n";
}

echo "</table>";

Just look at how much nicer and more concise that code looks and it's actually easier to read! Would you agree?

Upvotes: 4

Related Questions