PDO UPDATE query does not update table - php

The code in question is like this:
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_POST['id'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
}
if (empty($title) or empty($content) or empty($id)) {
$error = 'All fields are required!';
} else {
try {
$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ? WHERE article_id = ? ");
$query->bindValue(1, 'title');
$query->bindValue(2, 'content');
$query->bindValue(3, 'id');
$query->execute();
header('Location: index.php');
} catch (PDOException $e) {
print_r($e->errorInfo);
die();
}
}
}
It gives me no error whatsoever and the table does not update.
P.S. I am quite new to PHP in general so please bear with me if my errors are somewhat trivial, I just don't have anyone else to ask.

If you are new to PHP then I would suggest you try an alternative way of executing queries with placeholders (?) since it is much simpler.
First set up your connection.
try {
# First let us connect to our database
$db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", []);
} catch(\PDOException $e){
echo "Error connecting to mysql: ". $e->getMessage();
}
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Now call prepare/execute methods like:
$stmt = $db->prepare("
UPDATE articles
SET article_title = ?, article_content = ?
WHERE article_id = ?
");
$stmt->execute(array($article_title, $article_content,$article_id));
if($stmt->rowCount()) {
echo 'success';
} else {
echo 'update failed';
}

$query->bindValue(1, 'title');
$query->bindValue(2, 'content');
$query->bindValue(3, 'id');
The second value to bindValue should be the value, not the name of the value, something like;
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $id, PDO::PARAM_INT);

Related

Table value are not changing

There is my code of EDIT.php DB_Functions,and g.php..I'm not geting where is the fault is anyone here who can help me to find out mistake on my code
Every things happen as easy but change in table is not reflecting..my SQL query is working properly on XAMP server..
It may be silly mistake but not able to find it..
edit.php
<?php
//error_reporting(0);
include("class_db.php");
include_once('DB_Functions.php');
if (isset ($_GET['edit_id']))
{
$id=$_GET['edit_id'];
{
if(isset($_POST['nam']))
{
$id =($_POST['edit_id']);
$name=($_POST['name']);
$lastname=($_POST['lastname']);
$email=($_POST['email']);
$duser=($_POST['duser']);
$pass=($_POST['pass']);
$mob=($_POST['mob']);
$website=($_POST['website']);
$result = file_get_contents('http://localhost/rajju/demo/webservises/webservises/webservices/g.php?action=update_details&id='.$id.'&name='.$name.'&lastname='.$lastname.'&email='.$email.'&duser='.$duser.'&pass='.$pass.'&mob='.$mob.'&website='.$website);
$result = json_decode($result, true);
if($result == 'success'){
header("location:http://localhost/rajju/demo/webservises/webservises/webservices/list.php");
}
else{
print_r($result);
}
}
}
}
$select =mysql_query("select * from users where id=$id");
$var = mysql_fetch_object($select);
?>
DB_Functions.php
public function updateUser($id,$name,$lastname,$email,$duser,$pass,$mob,$website)
{
$app_list =mysql_query("UPDATE users SET name='".$name."',lastname='".$lastname."',email='".$email."',duser='".$duser."',pass='".$pass."',mob='".$mob."',website='".$website."' WHERE id='".$id."'");
if ($app_list) {
return true;
} else {
return false;
}
}
g.php
else if($tag == 'update_details')
{
$db = new DB_Functions();
//$id = ($_GET['id']);
$name=($_GET['name']);
$lastname=($_GET['lastname']);
$email=($_GET['email']);
$duser=($_GET['duser']);
$pass=($_GET['pass']);
$mob=($_GET['mob']);
$website=($_GET['website']);
//exit (json_encode($name));
if ($db ->updateUser($name,$lastname,$email,$duser,$pass,$mob,$website))
{
exit (json_encode('success'));
}else
{
exit (json_encode('errorzz'));
}
}
The following should work. Note this still wont totally protect you against xss and other attacks. However its a lot better than using mysql_query!! Additionally, you should sanatise and check your incoming $_GET params and Salt+Hash your passwords.
<?php
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE users SET name=:name, lastname=:lastname, email=:email, duser=:duser, pass=:pass, mob=:mob, website=:website, WHERE id=:id";;
$st = $conn->prepare( $sql );
$st->bindValue(":name", $name, PDO::PARAM_STR);
$st->bindValue(":lastname", $lastname, PDO::PARAM_STR);
$st->bindValue(":email", $email, PDO::PARAM_STR);
$st->bindValue(":duser", $duser, PDO::PARAM_STR);
$st->bindValue(":pass", $pass, PDO::PARAM_STR);
$st->bindValue(":mob", $mob, PDO::PARAM_STR);
$st->bindValue(":website", $website, PDO::PARAM_STR);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->execute();
?>

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

PDO Execute Statement Times Out

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...

php pdo not updating table

Iv been at this for hours, and it still wont work
i am trying to update a table
im not getting any errors
this is the account
<?php
if(isset($_POST['editfirst'])){
$delivery_option = $_POST['delivery_option'];
$about = $_POST['about'];
$SharersSignup->updateProfile($delivery_option);
echo 'ok';
}
?>
this is the function
$query = $this->pdo->prepare('UPDATE `sharers` SET delivery_option = ?, WHERE random = ?');
$query->bindValue(1, $delivery_option);
$query->bindValue(2, $_SESSION['logkey']);
try {
$query->execute();
}
catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
The problem is that you have a trailing comma in SET delivery_option = ?, <=
Remove it.

how to return a value from a method inside another method php

i got two methods.one method is to insert data and the other one is to get the id of the inserted data. i tried several test but it doesn't give any return value.is it possible to pass a return value from another method?
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
//$log = $this->getSessionID($email);
return $this->getSessionID($email);
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
public function getSessionID($email) {
try {
//global $bcrypt;
$query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");
$query->bindValue(1, $email);
$query->execute();
$data1 = $query->fetch();
$id = $data1['id'];
//echo $id;
return $id;
} catch(PDOException $e) {
die($e->getMessage());
}
}
and the returning page is here:
if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
session_regenerate_id(true);
$_SESSION['id'] = $data;
//print_r($_SESSION);
header('location: registry.php');
exit();
}
Use the lastInsertID() method on your query object rather than a second query
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
$insertId = $query->lastInsertId(); // <!-- Use this instead of a second query
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
Its also important to note that you are not inserting the 'email address' into your database, so there is no way for the query to find it by that field if you were to use another SELECT statement. You might want to complete your INSERT statement.

Categories