簡體   English   中英

PHP PDO函數更新值插入錯誤

[英]PHP PDO function update value insertion error

我正在嘗試創建一個名為update的函數來更新信息。 但是我搞砸了插入數據的更新查詢語句部分。 它不返回任何東西。 數據庫表名稱=“ test_table”。 這是我桌子上的照片,

在此處輸入圖片說明

function update( $con, $tbl_name, $colName, $colValue, $whereWhat, $equalsThis) {

    if( count($colName) > 0 && count($colValue) > 0 ) {
        if( count($colName) === count($colValue) ) {
            if( mb_strlen($tbl_name) > 0 ) {
                if( mb_strlen($whereWhat) > 0 ) {
                    if( mb_strlen($equalsThis) > 0){

                        for( $i = 0; $i < count($colName); $i++ ) {
                            if( mb_strlen($colName[$i]) > 0 && mb_strlen($colValue[$i]) > 0 && strpos($colName[$i], "=") !== false && strpos($colName[$i], "?") !== false ) {
                                $colName[$i]  = trim($colName[$i]);
                                $colValue[$i] = trim($colValue[$i]);
                            } else {
                                return "Doesn't contain = or wrong length";
                            }
                        }

                        $query = sprintf("UPDATE %s SET %s WHERE %s = %s",
                                 trim($tbl_name),
                                 array_values($colName),
                                 trim($whereWhat),
                                 trim($equalsThis)
                        );

                        $q = $con->prepare($query);
                        $q->execute(array_values($colValue) );

                        return "Worksz";

                    } else {
                        return "equalsThis identifier Required "; 
                    }
                } else {
                    return "whereWhat identifier Required "; 
                }
            } else {
                return "Table name required";
            }           
        } else {
            return "Require Same Arr len";
        }
    } else {
        return "wrong arr";
    }
}// end of function update();

這將調用該函數。 格式應如下所示!

//UPDATE test_table SET col1 = ?, col2 = ? WHERE col2 = 1b;
echo update( $con, "test_table", array("col1 = ?,", "col2 = ?"), array("col1Val", "colVal2"), "col2", "1b");

$ where列名對行的指示是什么。 $ equals這是列的值。

我認為將類與錯誤處理程序功能結合使用會更好地滿足您的需求(希望您對類有所了解,但如果需要,可以擺弄這個類):

<?php
    // This function purely returns errors
    function error_handler($error = false) {
            switch($error) {
                    case ('001'):
                        return "No values exist";
                    case ('002'):
                        return "Table name required";
                    case ('003'):
                        return "Where values required";
                }
        }

    // This engine does the sql assembly/execution and can be expanded on.
    class QueryEngine
        {
            public      $error;
            public      $statement;

            protected   $con;
            protected   $sql;

            public  function __construct($con = false)
                {
                    // It is presumed you are using an object connection
                    if(!is_object($con))
                        die("Invalid database connection.");
                    // Assign connection variable
                    $this->con  =   $con;
                }

            public  function update($table = false)
                {
                    $this->error    =   false;
                    $table          =   trim(preg_replace('/[^a-zA-Z0-9\_\-\.]/',"",$table));
                    $this->sql      =   array();

                    if($table == false || empty($table)) {
                            $this->error['table']   =   error_handler('002');
                            return $this;
                        }

                    $this->sql[]    =   "update";
                    $this->sql[]    =   "`$table`";

                    return $this;
                }

            public  function set($array = false)
                {
                    if(!is_array($array) || (is_array($array) && empty($array))) {
                            $this->error['values']  =   error_handler('001');
                            return $this;
                        }

                    $this->sql[]    =   "set";

                    foreach($array as $key => $value) {
                            $this->bind[":".$key]   =   $value;
                            $setvals[]              =   "`$key` = :$key";
                        }

                    if(isset($setvals))
                            $this->sql[]    =   implode(", ",$setvals);

                    return $this;
                }

            public  function where($array = false, $oper = "and", $comp = "=")
                {
                    if(!is_array($array) || (is_array($array) && empty($array))) {
                            $this->error['values']  =   error_handler('003');
                            return $this;
                        }

                    if(!in_array("where",$this->sql))
                        $this->sql[]    =   "where";

                    $i = 0;
                    foreach($array as $key => $value) {

                            $this->bind[":where".$i]    =   $value;
                            $whereset[]                 =   "`$key` ".$comp." :where".$i;
                            $i++;
                        }

                    if(isset($whereset))
                        $this->sql[]    =   trim(implode($oper." ",$whereset));

                    return $this;
                }

            public  function Combine()
                {
                    $this->statement    =   implode(" ",$this->sql);
                    return $this;
                }

            public  function write()
                {
                    $this->Combine();

                    if($this->error == false) {
                            $query      =   $this->con->prepare($this->statement);
                            $query->execute($this->bind);
                        }

                    return $this;
                }
        }

使用方法:

// Create a new instance. $con is your PDO connection (obviously)
$engine =   new QueryEngine($con);
// Assign the bulk of the method chain to $query. You could chain it all together
// but this way you can do quick error check before trying the sql execute`
$query  =   $engine ->update("test_table")
                    ->set(array("col1"=>"value1","col2"=>"value2"))
                    ->where(array("col1"=>"value3"));

// If the error variable is still false, try inserting into database
if($query->error == false) {
        // This is just a direct access to the final query statement
        //echo $query->Combine()->statement;
        // Will try and write to database
        $query->write();
    }
// If there is an error, show the error.
// The errors can be expanded out.
else
    print_r($query->error);
?>

成功的sql匯編:

// SQL statement
update `test_table` set `col1` = :col1, `col2` = :col2 where `col1` = :where0
// Bind array
Array
(
    [:col1] => value1
    [:col2] => value2
    [:where0] => value3
)

執行失敗(缺少信息):

Array
(
    [table] => Table name required
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM