Best way to write PHP SQL Update Statement

喜你入骨 提交于 2020-01-02 16:19:34

问题


I have this PHP SQL statement:

$updateCategory = "UPDATE category 
                   SET name=".$name.", description=".$description.",
                       parent=".$parent.", active=".$active." 
                   WHERE id=".$catID."";

What is the best way to write this?

Thanks,

Chris.


回答1:


I suggest you use prepared statements instead of concatenating the query string together:

$sql = 'UPDATE 
           category
        SET
           name=:name,
           description=:description,
           parent=:parent, 
           active=:active
        WHERE
           id=:catID';

if you are using PDO, which I strongly suggest, you would then call it like this:

$params = array(
    ':name'        => $name,
    ':description' => $description,
    ':parent'      => $parent,
    ':active'      => $active,
    ':catID'       => $catID
);

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

You might ask, "why all this hassle?" The advantages of this approach are quite overwhelming:

  • You don't have to care about SQL injection, since the database driver now handles the correct transformation of the input parameters
  • You don't have to care about escaping special characters, but you can concentrate on what you want to achieve rather than on how to achieve it :-)



回答2:


You could format it like this to make it more readable.

$updateCategory = "
    UPDATE
        category
    SET
        `name` = '" . $name . "',
        `description` = '" . $description . "',
        `parent` = '" . $parent . "',
        `active` = '" . $active . "'
    WHERE
        `id` = '" . $catID . "'";



回答3:


I find that concatenating queries causes me major headaches with syntax errors-- all those quotes and dots sprinked around like pepper. Here's how I would write the query:

$updateCategory = "
    UPDATE category     
    SET catname = '$name', description = '$description', 
        parent = '$parent', active = '$active'
    WHERE id = '$catID'"; 

Note that "name" is a reserved word and should not be used as a column name. Also if id is an integer, $catID doesn't need to be quoted.




回答4:


You can try:

$update = "update table_name SET name = '$name', email = '$email', password = '$password', phoneno = '$phoneno' WHERE id = '$id'";



来源:https://stackoverflow.com/questions/5433561/best-way-to-write-php-sql-update-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!