Is this this mysql/php correct to delete a row?
<?php
$id = $_POST['dr'];
$dbhost = 'star***.***.edu';
$dbuser = '***4123';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysq开发者_运维百科l_error());
}
$sql = "DELETE FROM address
WHERE idnum=\"".$id\"";
mysql_select_db('***4123');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
So just need some help figuring out if this is syntacticly correct. what should be sent through ajax is the id-number of the row i want to be deleted in the table address
Your query syntax looks incorrect, especially since your escaping of the "
is completely off. As well as you should be using single quotes within your query for string delimiters rather than the double quotes which you are using.
$sql = "DELETE FROM address WHERE idnum = " . $id;
This should work. This is assuming that id is numeric (i.e. an integer, float, decimal, etc.). You should always validate the provided data or at least sanitize before bringing it anywhere near the database or else someone could easily SQL inject your site. A quick cleaning which should be available is to cast the posted value as an int.
$id = (int) $_POST [ 'dr' ];
Use PDO. Easier error handling and better way to sanitize data:
<?php
try {
$db = new PDO ('mysql:host=star***.***.edu;dbname=***4123', '***4123', '*****');
}
catch (Exception $e)
{
die('Could not connect: ' . $e->getMessage());
}
$statement = $db->prepare('DELETE FROM address WHERE idnum=?');
$statement->bindParam(1, $_POST['dr']);
if (false === $statement->execute())
{
die('Could not delete data: ' . print_r($pdo->errorInfo(),true));
}
PDO automatically closes the connection, so there's nothing more to do.
<?php
$id = mysql_real_escape_string($_POST['dr']);
$dbhost = 'star***.***.edu';
$dbuser = '***4123';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM address
WHERE idnum= '$id' ";
mysql_select_db('***4123');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
Try to use MySQLi, Prepared Statement and never trust an input
精彩评论