0

I'm trying to update a table using this query but does not seem to work.

  $query="UPDATE product SET qty = (qty - '$qty') WHERE barcode = '$barcode'";  
  $result = $this->db->conn_id->prepare($query);
  $result->execute();  

I've tried placing the query inside a try catch block but it does not throw any error. The issue is with the implementation in CodeIgniter as this query is working when executed outside codeigniter.

2
  • What is conn_id referencing to? I do not see this in the examples in the documentation. Commented Dec 27, 2012 at 15:21
  • If row affected is zero ,i guess the query is correct,see if the value of the barcode variable exists in the database Commented Dec 27, 2012 at 15:55

1 Answer 1

1

Looking at your code there are a few things.

You aren't using the prepared statement right. The benefit to using a prepared statement is passing in the variables you need with a different function so you can escape them correctly. Consider the following:

$query="UPDATE product SET qty = (qty - ':qty') WHERE barcode = ':barcode'";  

$stmt = $this->db->conn_id->prepare($query);

$stmt->bindParam(':qty', $qty, PDO::PARAM_STR);
$stmt->bindParam(':barcode', $barcode, PDO::PARAM_STR);

$stmt->execute();  

echo "Rows affected: " . $stmt->rowCount();

Here we take the query and setup the parameters within. Then we bind the variables to the statement so they are escaped properly. After that we can execute the statement and then use the fetch() function to get our response. The enumeration passed in will return the results as an associative array.

Sign up to request clarification or add additional context in comments.

8 Comments

Parts of this answer reference this SO question
thanks for the correction, but still it doesnt update my table.
Updated my answer. What is the row count for your query?
Rows affected: 0, ive tried placing static value for quantity but still doesnt work.
What happens when you do var_dump($this->db->conn_id). Are you sure the record exists in the DB that you are trying to update?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.