Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

PHP MYSQL -> UPDATE column with variable if that variable isn't null or empty

Sorry, but i'm new to PHP, so i will look like a noob.

As the title says, i made this method which updates user data:

function update($userid, $name){
Try{

    $stmt=$this->db->prepare("UPDATE users
                          SET 
                          name=:name,
                          WHERE userid=:userid");
    $stmt->execute(array(':name'=>$name));

   } Catch(PDOException $e){
     echo $e->getMessage();
  }
  }

That code is working right, but i want to know if it's possible, the "name" column just update if the variable coming from:

$user->update($userid, $name);

From $name, is not null or not empty. If it's null or Empty, the MYSQL UPDATE function should not be done.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this instead.

function update($userid, $name) {
    try {
           if (!empty($name) and !empty($userid)) {
           $stmt = $this->db->prepare("UPDATE users
                                    SET 
                                    name=:name
                                    WHERE userid=:userid");
           $stmt->execute(array(':name' => $name, ':userid' => $userid));
           }
    }
    Catch(PDOException $e) {
        echo $e->getMessage();
    }
}

Explanation

  1. Removal of the trailing comma. As stated by @Fred -ii- you had a trailing comma in your SQL query after the SET (i.e SET name=:name,).
    The comma in SQL queries are used to separate multiple updates from one another so UPDATE table SET col1 = "val1", col2 = "val2" and so on. Since you are only updating one column, you don't need the comma
  2. The empty method checks whether the variable $name has been set and is not false. See documentation.
  3. Removed the SQL-Injection-Vulnerable in :userid=$userid

Why i think it is better to have an if-statement inside the function

  1. A function should be reusable and it costs nothing to call a function
  2. In clean code you should avoid using if-statements, which means, you should not always have surround an if-statment before calling a function which could be called in other parts of the code, too. What happens when you add another parameter?
  3. I know this is discussable.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...