No Update done with PDO php - php

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";
}

Related

Error with single quoted string and mysqli_real_scape_string

I am trying to save a string on my database: italo's house
but it's not working. my code:
include 'conexao.php';
$organizacao = mysqli_real_escape_string($con, $_POST['organizacao']); //italo's house
$result = mysqli_query($con, "update organizacao set organizacao = '".$organizacao."'");
if (!$result) {
throw new Exception(mysqli_error($con)."update organizacao set organizacao = '".$organizacao."'";
}else{
header('location:feira.php');
}
mysqli_close($con);
I receive a blank page
Using a prepared statement will resolve the issue with quotes and at the same time help protect you from SQL injection. Try this:
$organizacao = $_POST['organizacao'];
$stmt = $con->prepare("update organizacao set organizacao = ?");
$stmt->bind_param('s', $organizacao);
if (!$stmt->execute()) {
throw new Exception($stmt->error ." update organizacao set organizacao = '".$organizacao."'");
}else{
header('location:feira.php');
}

Updating database using dropdown without using a submit button

I'm trying to update the table status value whenever I make a selection from the dropdown list.
The problem is I'm having a syntax error on my update query. I've read stuff about syntax error and I can't quite understand it. I think I'm gonna need a more specific help. Here's what I've done:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "UPDATE tickets SET status = '$status' WHERE id = $id";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
else
{
echo "unknown index: 'status'";
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
And here's my table schema:
You are not performing prepared statements properly. You need to add the placeholder in the query and not the variables. The variables should be added in the execute() line.
$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));
Also FYI, $id is undefined.
Try Changing this:
$query = "UPDATE tickets SET status = $status WHERE id = $id";

getting session into each page

i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help
This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo

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;
?>

Button to update MySQL column not working

I want to update my database with an SQL statement once someone clicks a button on the website. I've tried something, no success. Can you guys help me ? Here's the code:
http://pastebin.com/D0S83Jgh
Don't know if I made this question correctly, I'm new here.
Your prepared statement is wrong.
The code I use with pdo to do a query is this:
$sqlUpd = $upd->prepare("UPDATE league_signups SET approved='1' WHERE id = :id");
$q->bindParam(':id', $id, PDO::PARAM_STR);
$q->execute();
Should work like a charm.
Get this code out of the main loop: while($row = $q->fetch(PDO::FETCH_ASSOC)) {}
<?php
include('pdoconnect.php');
$id = isset($row['id'];
if(isset($_REQUEST['approve']))
{
$sqlUpd = "UPDATE league_signups SET approved='1' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
if(isset($_REQUEST['unapprove']))
{
$sqlUpd = "UPDATE league_signups SET approved='0' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
?>
Put this code after the loop ending or the beginning of your code...
The data you want to update comes from the checkbox am I right? then you may want to make a loop to update all the values selected with checkbox to the corresponding action 'approve' or 'unapproved'
remove include('pdoconnect.php'); its utterly unnecessary if you are including this file from the beginning already
<?php
// checkbox[] it's an array...
$UpdateIDs = (isset($_REQUEST['checkbox'])) ? $_REQUEST['checkbox'] : [];
// check if $_REQUEST['approve'] is set else check if $_REQUEST['unapprove'] is set else set $approve to null;
$approved = (isset($_REQUEST['approve']) ?
$_REQUEST['approve'] :
(isset($_REQUEST['unapprove'])) ? $_REQUEST['unapprove'] : null;
if(!is_null($approved))
{
try {
foreach($UpdateIDs as $ID)
{
$stmt = $upd->prepare("UPDATE league_signups SET approved=:approved WHERE id=:id");
$stmt->execute([
':approved' => $approved,
':id' => $ID
]);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}

Categories