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...
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";
}
I want to update table with max three value and minimum with two values.How it would be possible to update table. I Get values from form, there are three fields for three students. Now all of them having same value when i update them in the database. Now i am trying this why. Dont know it works or not
See my page
$s1_name=$_POST['s1_name'];
$s2_name=$_POST['s2_name'];
$s3_name=$_POST['s3_name'];
$query="update students SET Name=:Name
WHERE ProjectID='$id'
";
try
{
$stmt = $conn->prepare( $query );
$stmt->bindParam(':Name', $s1_name);
$stmt->bindParam(':Name', $s2_name);
$stmt->bindParam(':Name', $s3_name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
It does not work this way. The way you are doing it will result in the query only updating it for $s3_name.
You will have to do your try/catch statement for each query:
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
I've searched all over the net for examples on performing a sql update on clob fields; I believe the example I'm using is the simplest one that should work but so far none have worked. I'm trying to insert a base64 encoded image into the clob field in oracle. Below are the function and the array of clob entries. I've checked the table and verified that no update has occurred on the clob field.
// update row with new clob values
private function clobUpdate($clobArray){
try {
foreach ($clobArray as $item) {
$query = "UPDATE ". static::$table ." SET ". $item["clobField"] ." = EMPTY_BLOB() WHERE ID = :ID RETURNING ". $item["clobField"] . " INTO :blob";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $item["id"]);
$stmt->bindParam(':blob', $item["clobValue"], PDO::PARAM_LOB);
$blob = NULL;
$this->db->beginTransaction();
$stmt->execute();
$this->db->commit();
print_r($blob);
die();
}
} catch(Exception $e){
throw new Exception($e);
}
}
Array
(
[0] => Array
(
[clobField] => 0
[clobValue] => data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAAABrrFhUAAAAM1BMVEWxvsa7xs7CzNPM1drT2t/a4OTd4+fn6+7g5enW3eLFz9W/ydC0wcnP1924xMvJ0tjk6OzcN6J1AAAED0lEQVR4AezBgQAAAACAoP2pF6kCAAAAAAAAAAC4vbvLgV3FgQBcCYHiLzT7X+28XWkermbOSeLYMd8OqAA2Ust9u20PR0z8R44l1AYX+n5G/ot01oFPG7/I/yGd23dXn/h/yZ/MoBX+gVTxLTXzD+XQ8Rl75l+YAd+wRf6lvMO+fvKCMmDclnjJ3GHaj5cdMOzgDVKHUT3xFnOzu37PCfREek6gJ9JzAj2RrhNIvNkc9uufo2r44wMKzNj4iB+M6JnP2G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Lpq+AwVuQX6efB9oqhds/Ly2AlgBrAD+3XB+Ca4yiMSPS/hv/wEp/tUncVv5oQAAAABJRU5ErkJggg==
[id] => 25
)
)
***** update
Per Fred's error handling link and this 2007 patch I'm now able to update my clob. Updated function below:
// update row with new clob values
private function clobUpdate($clobArray){
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
foreach ($clobArray as $item) {
$query = "UPDATE ". static::$table ." SET ". $item["clobField"] ." = :CLOB WHERE ID = :ID";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':ID', $item["id"]);
$stmt->bindParam(':CLOB', $item["clobValue"], PDO::PARAM_STR, strlen($item["clobValue"]));
$blob = NULL;
$this->db->beginTransaction();
$stmt->execute();
$this->db->commit();
print_r($blob);
die();
}
} catch(PDOException $e){
echo "Exception ". $e->getMessage();
throw new Exception($e);
}
}
NOTA: Posting as a community wiki to mark the question as solved.
You are using :ID and :id. Those are case-sensitive.
WHERE ID = :ID ... bindParam(':id', => bindParam(':ID',
Use PDO's error handling http://php.net/manual/en/pdo.error-handling.php
Yet, from the link you found about a patch, seems to also have contributed to successfully updating your database.
As per your comment:
"Per Fred's error handling link and this 2007 patch I'm now able to update my clob. Updated function below:"
// update row with new clob values
private function clobUpdate($clobArray){
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
foreach ($clobArray as $item) {
$query = "UPDATE ". static::$table ." SET ". $item["clobField"] ." = :CLOB WHERE ID = :ID";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':ID', $item["id"]);
$stmt->bindParam(':CLOB', $item["clobValue"], PDO::PARAM_STR, strlen($item["clobValue"]));
$blob = NULL;
$this->db->beginTransaction();
$stmt->execute();
$this->db->commit();
print_r($blob);
die();
}
} catch(PDOException $e){
echo "Exception ". $e->getMessage();
throw new Exception($e);
}
}
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;
?>
I have the following SQL query:
UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4'
WHERE Country = 'Algeria'
When I run this query via MySQL workbench it executes fine.
I am trying to run this via a website / PHP however, and am attempting to execute the query in the following way:
$sql = "UPDATE uploads SET UserName='$user_data[name]', UserEmail='$user_data[email]', UploadCount='$user_data[FilesUploaded]' WHERE Country = '$country'";
echo $sql;
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
The SQL query is being built via variables here, however I copy / pasted the echo of $sql into workbench to check that there were no syntax errors creeping in, the echo of $sql is what I pasted above.
When I run it via the web application, I get 0 row affected and the UPDATE is not made, where am I going wrong?
Thank you
UPDATE: A new paramatarized version of the PDO:
$sql = "UPDATE uploads SET ";
$sql .="UserName = :name,
UserEmail = :email,
UploadCount = :FilesUploaded";
$sql .=" WHERE Country = '$country'";
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":name", $user_data['name']);
$stmt->bindParam(":email", $user_data['email']);
$stmt->bindParam(":FilesUploaded", $user_data['FilesUploaded']);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
It looks like you're trying to insert information from an array while it's in quotes. Try this:
$sql = "UPDATE uploads SET UserName='".$user_data['name']."', UserEmail='".$user_data['email']."', UploadCount='".$user_data['FilesUploaded']."' WHERE Country = '$country'";