user10445269
user10445269

Reputation:

No Update done with PDO 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>";
        }

Upvotes: 0

Views: 46

Answers (1)

Sajjad Ali
Sajjad Ali

Reputation: 304

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

Upvotes: 2

Related Questions