Home >Backend Development >PHP Problem >How to delete data from php database

How to delete data from php database

藏色散人
藏色散人Original
2020-11-24 10:17:052556browse

How to delete data from the PHP database: first create a code file; then execute the "SQL DELETE" statement through the PHP function "mysql_query" to delete data from the MySQL table.

How to delete data from php database

Recommendation: "PHP Video Tutorial"

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, This method works for all brands of computers.

Deleting data from the MySQL database

You can delete data from the MySQL table by executing the SQL DELETE statement through the PHP function mysql_query.

The following is a simple example to delete records from the employee table. The conditional clause used when deleting records should target a certain record in any table.

The following example uses the primary key to match records in the employees table.

Example

Try the following example to understand the delete operation. You need to provide an employee ID to delete an employee record from the employee table.

  <html>
    <head>
    <title>Delete a Record from MySQL Database</title>
    </head>
    <body>
    <?php
    if(isset($_POST[&#39;delete&#39;]))
    {
    $dbhost = &#39;localhost:3036&#39;;
    $dbuser = &#39;root&#39;;
    $dbpass = &#39;rootpassword&#39;;
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(! $conn )
    {
      die(&#39;Could not connect: &#39; . mysql_error());
    }
    $emp_id = $_POST[&#39;emp_id&#39;];
    $sql = "DELETE employee ".
           "WHERE emp_id = $emp_id" ;
    mysql_select_db(&#39;test_db&#39;);
    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
      die(&#39;Could not delete data: &#39; . mysql_error());
    }
    echo "Deleted data successfully\n";
    mysql_close($conn);
    }
    else
    {
    ?>
    <form method="post" action="<?php $_PHP_SELF ?>">
    <table width="400" border="0" cellspacing="1" cellpadding="2">
    <tr>
    <td width="100">Employee ID</td>
    <td><input name="emp_id" type="text" id="emp_id"></td>
    </tr>
    <tr>
    <td width="100"> </td>
    <td> </td>
    </tr>
    <tr>
    <td width="100"> </td>
    <td>
    <input name="delete" type="submit" id="delete" value="Delete">
    </td>
    </tr>
    </table>
    </form>
    <?php
    }
    ?>
    </body>
    </html>

The above is the detailed content of How to delete data from php database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn