Tuesday 5 December 2017

mysql - cannot delete record with php script

itemprop="text">

when i go to produkdelete.php i can
view the record that i want to delete, but when i confirm to delete there is no deleted
record



this is my script
:



$key =
@$_GET["key"];

case "I": // Get a record to
display


$tkey = $key;
$strsql = "SELECT *
FROM `produk` WHERE `id`=".$tkey;

$rs = mysql_query($strsql,
$conn) or die(mysql_error());

if (mysql_num_rows($rs) ==
0)
{
ob_end_clean();
header("Location:
"."produklist.php");
}


$row =
mysql_fetch_assoc($rs);
$x_id = $row["id"];
$x_kdprod =
$row["kdprod"];
$x_namaprod = $row["namaprod"];
$x_diskripsi =
$row["diskripsi"];
$x_harga = $row["harga"];


mysql_free_result($rs);
break;


case "D": //
Delete

// Open record
$tkey = $key;
$strsql
= "DELETE FROM `produk` WHERE `id`=".$tkey;

$rs =
mysql_query($strsql, $conn) or die(mysql_error());


mysql_free_result($rs);

mysql_close($conn);


ob_end_clean();
header("Location: produklist.php");

break;


the key
variable is send from
"produkdelete.php?key=".urlencode($row["id"]);



and
everytime i run this the output just come like this :




You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near '=' at line 1


class="post-text" itemprop="text">
class="normal">Answer



In SQL
Management Studio this won't
run.



$strsql = "DELETE
FROM
produkWHEREid=".$tkey;



Lose
the ` and it should execute.



With PDO for added
security (explanation
below)




 $myServer =
"put url to your server here";
$myDB = "put name of database
here";
$name = "login name db";
$pw= "password
db";

try
{
$dbConn = new
PDO("mysql:host=$myServer;dbname=$myDB", $name, $pw);
}


catch( PDOException $Exception )
{
//Uncomment code to show
error
//var_dump($Exception);
}

function
doPDOQuery($sql, queryArguments = array())
{
$sth =
$db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

$sth->execute($queryArguments );

}

$sql =
'SELECT * FROM produk WHERE id= :id';
doPDOQuery( $sql, array(":id" ->
$tkey) );


This should
execute on your server. It's using the href="http://php.net/manual/en/book.pdo.php" rel="nofollow noreferrer">PDO
module for creating prepared queries. That means that the query
itself is created by the database-driver itself. This prevents
SQL-injection. This is a reason why
MySQL_functions are
deprecated.



For delete,
update and insert the code above is
sufficient. You need to do a $sth->fetchAll() to retrieve
rows from a
select.




href="https://stackoverflow.com/questions/16859477/why-are-phps-mysql-functions-deprecated">Why
are PHP's mysql_ functions deprecated?



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...