0

My update query is

"UPDATE registration SET `dob` = '".$theDate."' , pwd='".$_REQUEST['n_password']."', name='".$_REQUEST['n_name']."' where id='".$_SESSION['id']."' "

Problem is that it is not necessary that user update all fields so if it happens there are null values coming from form and it will replace earlier value in database.

I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Om prks
  • 1
  • 1
  • 6
  • Isn't it so that you should employ all checks (both server-side and client-side) before any external data reaches your script? – verisimilitude Aug 25 '12 at 15:23
  • 1
    This looks horrible like one big SQL injection honeypot. Oh, and probably the `php` tag is missing, I guess? – Uwe Keim Aug 25 '12 at 15:29
  • SQL Injections: http://stackoverflow.com/questions/11939226/sql-injections-and-adodb-library-general-php-website-security-with-examples/12123649#12123649 – Ilia Ross Aug 25 '12 at 17:06
  • @LLIa now i understand that what is sql injection and now start using escaping input's but still not understand PDO what it exactly, i had gone through mysql pdo tutorial but not getting much.... – Om prks Aug 26 '12 at 07:31

1 Answers1

2

I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me

Don't issue an UPDATE query after you check each value, instead add that column to the query you're building, then execute just one UPDATE with only the columns that had values.

$dbh = new PDO('mysql:host=localhost;dbname=whatever', 'user', 'password');
$params = array();

$sql = "UPDATE REGISTRATION SET `dob` = ?";
$params[] = $theDate;

if (!empty($_REQUEST['n_password'])) {
  $sql .= ", `pwd` = ?";
  $params[] = $_REQUEST['n_password'];
}

if (!empty($_REQUEST['n_name'])) {
  $sql .= ", `name` = ?";
  $params[] = $_REQUEST['n_name'];
}

$sql .= " WHERE `id` = ?";
$params[] = $_SESSION['id'];

$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 1
    thanks a lot but i don't think that i can use PDO as i have not enough experience & knowledge and i have to finish project soon, but i will try it latter, if you have any other way then please let me know – Om prks Aug 26 '12 at 08:01
  • 1
    This is the complete code to use PDO to execute your query. There is nothing else to learn. – Dan Grossman Aug 26 '12 at 17:14
  • 1
    @DanGrossman - Thanks. Just wondering why you opted for ```!empty``` instead of ```isset``` in the if blocks ? – MarcoZen Aug 18 '21 at 12:18