Unable to perform Update sql from php - php

The following is my code
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "UPDATE usermaster SET Password=?, UserName=?, OwnerOrEmp=?, DBName=?, DeleteFlag=?, UpdateDate=? WHERE UserId = ?";
$sql = "UPDATE usermaster SET Password=:password, UserName=:userName, OwnerOrEmp=:ownerOrEmp, DBName=:dBName, DeleteFlag=:deleteFlag, UpdateDate=:updateDate WHERE UserId = :id";
$q = $pdo->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_STR, 8);
$q->bindParam(':userName', $name);
$q->bindParam(':password', $pass);
$q->bindParam(':ownerOrEmp', $ownEmp);
$q->bindParam(':dBName', $dbName);
$q->bindParam(':deleteFlag', $delEmp);
$q->bindParam(':updateDate', $curr_date);
$q = $pdo->prepare($sql);
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));
Database::connect();
}catch(PDOException $e){
//die($e->getMessage());
$db_error = "".$e->getMessage();
}
header("Location: ShainIndex.php");
}
Request your kind insight, this piece of code alone does not get executed and update is not executed...Thanks in advance.

your preparing same query twice
$q->bindParam(':updateDate', $curr_date);
// $q = $pdo->prepare($sql); //comment this line
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));

I finally began to debug each and every single variables value being inserted, as shown in the above bindParam(). It turned out that by default or due to some string handling there happened to a space(" ") being inserted into many many of the values of those variables.
So, what this space was causing was, that it did not allow the value to be matched on the database to the inputed data coming from the view.
Due to which especially the "id" field receive values with spaces...like " 00100001" although it is not easily visible it never matched with "00100001" value in the db's table.
Thus, this took me the whole day and almost cost me my job. In some place a small "-" broke down an entire satellite launching rocket.
So, I am in a way blogging my "Word of Caution" to all those whose life ticks on one tiny bit of characters.
Thanks to all those who provided their valuable inputs and time.

Related

PHP PDO Service No Data

I have the below REST web service that I am using to get user information from User table:
$name = htmlentities($_GET["name"]);
$name = strtoupper($name);
$dbh = new PDO("oci:dbname= $dbhost", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("select * from Users where username =:name");
$sth->bindParam(':name', $name);
$sth->execute();
$result = array();
$result["User"] = $sth->fetchAll((PDO::FETCH_ASSOC));
print_r ($result); //returns no data
When I print out the results, no data is returned. If I hard code a username value instead of using :name, then data comes back:
$sth = $dbh->prepare("select * from Users where username ='TESTUSER'");
I am not sure what I am doing wrong with the binding of the variable that is causing the SQL to run incorrectly. I tried using bindValue and bindParam and still returns no data. I am not recieving any errors, just no data.
UPDATE: It looks like the syntax is correct. Is there anything on the Oracle side that would prevent a prepared statement from being run?
I figured out why data wasn't returning on the query. The database has the username field set as a CHAR(8) and usernames that were being passed only had 7 characters so it was failing. I need to append a blank space at the end of the string for it to match.

Completely bizarre behaviour on MYSQLi update

A warning up front, this project is part of a reporting system for workers looking after people with some profound disabilities and there is some unsavoury language that I don't use in jest and wouldn't in such a forum unless it was completely pertinent. No offense is meant.
I don't know if I even expect an answer to this because it is so completely strange, but here goes... I have a pretty simple form editing a text field in a mysql database. The update code couldn't be simpler;
(after connecting to the database)
$stmt = $mysqli->prepare("UPDATE rep_evening SET rppe_notes = ? WHERE rppe_mrep = ?");
$stmt->bind_param('si', $_POST['enotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
header("Location: ../reports.php");
The code is probably pointless because it all works perfectly well UNTIL the words 'suck dicks' is somewhere in the text. Then it throws a 403 error which is seemingly triggered on the header return because the update works. I thought perhaps somebody had put a profanity filter in but if they did it's pretty useless because it doesn't matter what else is in there, and believe me there's some pretty unsavoury stuff, just those two words, with the plural on the latter word - the singular doesn't fire the error. The 2 words can be separated by up to 3 words and trigger the 403, but no more than 3.
There's nothing in error logs, no clues anywhere but it can be replicated any number of times.
MYSQL V5.6.30, PHP 5.4 if that's of interest.
Edit...
Here's the full processing page, there's 3 sections to the report and an approval tag for it to be viewed beyond admins;
<?php
include ('../includes/dbconn.php');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("UPDATE rep_day SET rppm_notes = ? WHERE rppm_mrep = ?");
$stmt->bind_param('si', $_POST['mnotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE rep_evening SET rppe_notes = ? WHERE rppe_mrep = ?");
$stmt->bind_param('si', $_POST['enotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE rep_overnight SET rppo_notes = ? WHERE rppo_mrep = ?");
$stmt->bind_param('si', $_POST['onotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE mreport SET mrep_approved = ? WHERE mrep_id = ?");
$stmt->bind_param('si', $_POST['approved'], $_POST['repid']);
$stmt->execute();
$stmt->close();
header("Location: ../reports.php");
?>

Player score update with PHP MySQL

I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work

update mysql database table fields with a single mysqli statement query

I have a database table and i am updating the table columns this way.
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$data['image'] = $this->replace_whitespace($data['image']);
foreach($data as $key=>$value){
$this->query = "UPDATE users SET $key=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('s', $value);
$this->statement->execute();
$this->statement->close();
}
}
Is it possible to update more than one table columns in one go. I tried this but in-vain.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('sss', $value1, $value2, $value3);
$this->statement->execute();
$this->statement->close();
}
Is there a better way doing this?
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$this->query = "UPDATE users SET fname=?, lname=?, email=?, tpin=?, image=?, address=? country=?, city=?, state=?, postal=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if ($this->statement) {
$this->statement->bind_param('ssssssssss', $data['fname'],$data['lname'],$data['email'],$data['tpin'], $data['file'], $data['address'],$data['country'],$data['city'],$data['state'], $data['post_code']);
$this->statement->execute();
$this->statement->close();
}
This is my real code.
Remove the "," after col3=?
This will fix the syntax error
$this->query = "UPDATE users SET col1=?, col2=?, col3=?, WHERE username='$username'";
You have an extra comma, meaning your SQL is reading "WHERE" as another column and everything gets messed up.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
Should work fine.
In response to the comment below, this is the correct way of going about it, so it must be a faulty variable somewhere, what error messages are you getting? (If any)
It could also be that one of the parameters you are binding is not a string. Regardless, we'd need a more in-depth example.
Is it possible to update more than one table columns in one go
Yes. Actually, updating many fields in one query is a very core feature of any DBMS. You can always expect it to be supported.
I tried this but in-vain.
Well, you have to try more, like we all do. After all, it's your job.
Two notes regarding your "real" code:
You have to bind ALL variables in the query, not only some of them
you have to configure mysqli to report errors:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I assume it works the same way as putting new values into the database.
Update a row mysql in php

Why does my PHP transaction not work?

I'm working on a school project creating a CMS for my portfolio site. I am having trouble getting my update function to work. I have a feeling it has something to do with the way I'm constructing my PDO Transaction. In my database I have a projects table, category table, and the associative content_category table. I'm able to insert my projects into those tables just fine. What I want to do is insert into my projects table then delete all records from the content_category table and finally insert the current category records into that associative table to complete the transaction. I do get my return statement "Project Updated" returned. But the tables aren't being updated. Any ideas anyone?
Here's the code:
This is a function in my Project class.
public function update(){
try {
$conn = getConnection();
$conn->beginTransaction();
$sql = "UPDATE project
SET project_title = :title,
project_description = :desc,
project_isFeatured = :feat,
project_mainImage = :image
WHERE project_id = :id";
$st = $conn->prepare($sql);
$st->bindValue(":id", $this->id, PDO::PARAM_INT);
$st->bindValue(":title", $this->title, PDO::PARAM_STR);
$st->bindValue(":desc", $this->description, PDO::PARAM_STR);
$st->bindValue(":feat", $this->isFeatured, PDO::PARAM_BOOL);
$st->bindValue(":image", $this->mainImage, PDO::PARAM_INT);
$st->execute();
$sql = "DELETE from content_category
WHERE content_id = :id";
$st = $conn->prepare($sql);
$st->bindValue("id", $this->id, PDO::PARAM_INT);
$st->execute();
$sql = "INSERT into content_category (content_id, cat_id)
VALUES (?,?)";
$st = $conn->prepare($sql);
foreach($this->categories as $key=>$value){
$st->execute(array(intval($projectID), intval($value)));
}
$conn->commit();
$conn = null;
return "Project updated";
}
catch(Exception $e) {
echo $e->getMessage();
$conn->rollBack();
return "Error... Unable to update!";
}
}
Your database engine for the tables needs to be INNODB. If you are using phpMyAdmin, it defaults to MyISAM. (I don't know if that will cause the updates not to go through or just the transaction line to be ignored. Edit: Pretty sure the documentation is saying that it will throw an error and not do anything if you beginTransaction on a myISAM)
In order to make sure you are not encountering a PDO error, you should set the PDO error reporting like this:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
There are functions in PDO such as prepare() which will either return false or throw a PDOException depending on what error mode is set. This way, it will throw an exception and you'll definitely know if you are having a problem!
Also, if your database doesn't support transactions (like MyISAM), the beginTransaction() function will return false. So, maybe add a check in there like:
if($conn->beginTransaction()) {
// Do transaction here
} else {
echo("Unable to use transactions with this database.");
}
Oddly enough, according to PHP documentation, you would be getting an exception if your database doesn't support transactions...
Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition).
Commit returns TRUE on success or FALSE on failure. You can check it. Also check for errorCode.

Categories