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;
?>
Related
I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}
My current code updates all values, and if there is an empty parameter it updates the corresponding field on the table to null. I want to update only the fields that have a value.
This is my code:
$sql = "
UPDATE drinks SET
name = :name, // Mojito -> Update it
description = :description, // Lorem ipsum.. -> Update it
glass_id = :glass_id, // NULL -> do not update
video_url = :video_url // NULL -> do not update
WHERE id = '$drinkId'
";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':glass_id', $glassId);
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}
you don't want to update those 2 fields when they are empty.
this code check if a field is null and only when it is not null it will add the field to the query, also the same for binding the value.
$sql = 'UPDATE drinks SET';
$sql = sql . 'name = :name,';
$sql = sql . 'description = :description';
if (!is_null($glassId))
$sql = sql . ',glass_id = :glass_id';
if (!is_null($videoUrl))
$sql = sql . ',video_url = :video_url';
$sql = sql . ' WHERE id = :drinkId';
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':drinkId', $drinkId);
if (!is_null($glassId))
$stmt->bindParam(':glass_id', $glassId);
if (!is_null($videoUrl))
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}
How can I echo how many records were updated with this code?
I know that I can do this in a common update:
echo $stmt->rowCount() . " records UPDATED successfully";
But the question here is, how to do it when there is multiple updates at the same time.
NOTE ABOUT POSSIBLE DUPLICATE: I already have explained that my question is different than: PDO were rows affected during execute statement
That solution is for a single update and it does not work in this code. What I ask is how to count when there is multiple updates.
try {
require_once 'connexion.php';
$stmt = $conn->prepare("UPDATE bookmarks
SET podcast=:podcast, text=:text
WHERE id=:id");
$stmt->bindParam(':podcast', $podcast);
$stmt->bindParam(':text', $text);
$stmt->bindParam(':id', $id);
$podcast = 1;
$text = "text 1";
$id = 147;
$stmt->execute();
// another row:
$podcast = 2;
$text = "text 2";
$id = 265;
$stmt->execute();
// echo " records UPDATED successfully";
}
catch(PDOException $e){
echo $e->getMessage();
}
Try this.
As you are doing multiple ->execute() you will have to capture the count of each ->execute() as you do it and then show the accumulated total count at the end
try {
require_once 'connexion.php';
$update_count = 0;
$stmt = $conn->prepare("UPDATE bookmarks
SET podcast=:podcast, text=:text
WHERE id=:id");
$stmt->bindParam(':podcast', $podcast);
$stmt->bindParam(':text', $text);
$stmt->bindParam(':id', $id);
$podcast = 1;
$text = "text 1";
$id = 147;
$stmt->execute();
$update_count += $stmt->rowCount();
// another row:
$podcast = 2;
$text = "text 2";
$id = 265;
$stmt->execute();
$update_count += $stmt->rowCount();
echo "$update_count records UPDATED successfully";
}
catch(PDOException $e){
echo $e->getMessage();
}
Try $stm->rowCount(). Source here: http://php.net/manual/en/pdostatement.rowcount.php
The question was already asked here as well: https://stackoverflow.com/a/10522575/2853903
I am having quite some trouble and am unable to find the source of the problem but I cannot send a simple update to my sqlite3 database which simply times out and doesn't do anything. It said thirty seconds at first but then I changed it to 5 minutes and it still wouldn't do anything to query through a simple 1 rowed sqlite table.
if (isset($_POST['apply']))
{
try {
$bio = $_POST['bio'];
$file_db = new PDO('sqlite:Secure/data.sqlite');
// Set errormode to exceptions
//$file_db->exec("SET CHARACTER SET utf8");
$file_db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
//
echo("$bio $name");
$sql = "UPDATE `users`
SET `profile` = :bio
WHERE `name` = :name
";
echo("2");
$statement = $file_db->prepare($sql);
echo("3");
$statement->bindValue(":bio", $bio);
echo("4");
$statement->bindValue(":name", $name);
echo("5");
$statement->execute();
echo("6");
$file_db = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
//$statement->bindValue(":profile", $profile);
//$statement->execute();
}
Remove the quotes from your bindValue() call:
$statement = $db->prepare($sql);
$statement->bindValue(':bio', $_POST['bio'], PDO::PARAM_STR);
$statement->bindValue(':name', $_POST['name'], PDO::PARAM_STR);
$statement->execute();
or
$statement = $db->prepare($sql);
$statement->execute(array(':bio' => $_POST['bio'],':name'=>$_POST['name']));
When doing updates, it is a good idea to check if it actually affected a row
if($statement->execute()){
echo 'success !';
if($statement->rowCount()>0){
echo 'record updated !';
}else{
echo 'no record updated !';
}
}else{
echo 'failed !';
}
It appears there was a variable being set in template.php called result, no idea why but I set this to null and all worked well...
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() .'}}';
}
?>