Search Help Board

PHP FAQ
PHP Articles
PHP Help
Bulletin Board

PHP Manual (NEW!)
First Time PHP'ers
Help with programming
Sql assignment help
PHP Homework Help


C# Help

 

Previous Page Page 4 of 4  

SQL Delete Function

This delete function will remove data from the database by specifying the table name and the where clause.


PHP Code:

<?php

define (DB_HOST, "CHANGE_THIS");
define (DB_NAME, "CHANGE_THIS");
define (DB_USER, "CHANGE_THIS");
define (DB_PASS, "CHANGE_THIS");

if (!strcmp(DB_HOST,"CHANGE_THIS")){
echo "You must setup your database settings. Change the defines DB_HOST, DB_NAME, DB_USER and DB_PASS\n";
exit;
}

/*
 * DeleteQuery
 * Desc: Delete data from the database.
 * Parms:
 *   $tableName - database table name.
 *   $where - SQL Where clause to specify which row(s) to delete.
 *   $debug - If true then return SQL query without executing.
 * Returns:
 *   Nothing on success.
 *   Error String on failure.
 */
Function DeleteQuery ($tableName, $where="", $debug=false)
{
$db = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if ($db == false){
return mysql_errno().": ".mysql_error()."<br>";
}

// Delete a row from the specified table.
if (!empty($where)){
if (!strstr(strtolower($where),"where ")) $where = "where $where";
}

$query = "delete from $tableName $where";

if ($debug){
@mysql_close($db);
return $query;
}

$stmt = mysql_db_query (DB_NAME, $query, $db);

if (!$stmt){
$error = mysql_error ($db);
}

@mysql_free_result ($stmt);
@mysql_close($db);

return $error;
}

?>

PHP Code:

<?php

// Sample call to new delete function.
$error = DeleteQuery ("employee", "where name='Kris'");
if (!empty($error)){
echo "Error: $error<br>\n";
}

?>

Previous Page Page 4 of 4