delete query doesn't work - php

I made a delete query. The delete query is used to delete posts made by the admin but if I click on the the delete button I go to a screen with object not found.
I will show the delete query:
include '../db/db.php';
$id = $_GET['0'];
$query = "DELETE FROM pages WHERE paginaNummer = :id";
$stmt = $dbcon->prepare($query);
$stmt->execute(array(':id' => $id));
$row=$stmt->fetch();
header("Location: http://127.0.0.1/cmsFenB/index.php");
Here is the db connection:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=register', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
?>
And here is the link that referrers to this script:
echo " <a class='delete' href='fucntions/admin/delete.php?id=" . $pageNumber . " '>Delete</a>";
I hope you can help me out with this problem.

You have a typo in the referrer link. It should look like this:
echo " <a class='delete' href='functions/admin/delete.php?id=" . $pageNumber . " '>Delete</a>";
$id=$_GET['0']; ? I think you meant something like $_GET['id']
$id=$_GET['id'];
$query = "DELETE FROM pages WHERE paginaNummer = :id";
$stmt = $db->prepare($query);
$stmt->execute(array(':id' => $id));

Related

delete mysql row by retrieving id PHP foreach

I've created a foreach statement that echos out some stuff about all users registered, how do I make a button that deletes that user from the row? I've tried this:
$query = "
SELECT id
, name
, bname
, email
, address
, agent
, status
, notes
FROM prospects
";
try {
$stmt = $db->prepare($query);
$stmt ->execute();
}
catch(PDOException $ex) {
die("Failed to run query. Tell the website owner!");
}
$rows = $stmt->fetchAll();
foreach($rows as $row) {
echo "<tbody>
<th>".$row['name']."</th>";
echo "BLAH BLAH BLAH!";
echo "<form method='post'><th><button type='submit' name='delete' class='btn btn-white btn-round btn-just-icon'>
<i class='material-icons'>remove_circle_outline</i>
<div class='ripple-container'></div>
</button></th></tbody></form>";
} $id = $db->prepare("SELECT id FROM example");
$id->execute();
$result = $id->fetch(PDO::FETCH_ASSOC);
if(isset($_POST['delete'])) {
try {
$sql = "DELETE FROM example WHERE id='".$result."'";
$db->exec($sql);
}
catch(PDOException $e) {
echo $sql . "<br />". $e->getMessage();
}
}
It returns this error:
Notice: Array to string conversion....
I know this is because I've grabbed the id and there is an array of ids that I've grabbed from the database? So how do I do delete a specific row when i click on the button?
You have to specify which element in array holds the id value.
Try:
$sql = "DELETE FROM example WHERE id='".$result['id']."'";

How to delete and update using php

Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>

Query doesn't insert value into DB

In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Delete From Table Name Stored As Variable?

After the user logs out, it basically deletes the all the data in their table that includes their id code in any of the rows.
$idcode = $_SESSION['idcode'];
$idicao = $_SESSION['idicao'];
if(isset($_POST['logout'])) {
$sql = "DELETE FROM $idicao WHERE idcode=".$idcode."";
mysql_query($sql);
}
session_unset();
session_destroy();
mysql_close($dbid);
header("Location: login.php");
?>
The variables are echoed on the page correctly, and session_start is at the top. The only problem is that the records from the tables are not being deleted.
change this line:
$sql = "DELETE FROM $idicao WHERE idcode=".$idcode."";
to
$sql = "DELETE FROM ".$idicao." WHERE idcode=".$idcode.";
and you should be good to go
Try this:
$idicao='yourtablename';
$sql = 'DELETE FROM '.$idicao.' WHERE idcode='.$idcode;
You are saying that the sql-variable outputs: DELETE FROM Test WHERE idcode=test
Test should be in single quotes like this:
$sql = "DELETE FROM ".$idicao." WHERE idcode='".$idcode."'";
$query = 'DELETE FROM ? WHERE idcode = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('ss', $idicao, $idcode);
$stmt->execute();
if (mysqli_connect_errno()) {
$obj->error = 'Error: ...your error msg...';
echo json_encode($obj);
exit;
}

Categories