如何在函数中传递空变量并更改其值

时间:2018-08-28 22:42:18

标签: php mysql pdo

我想传递一个包含空值的字符串,然后将其填充到函数中。 (我知道SQL注入)。另一方面,我想举一个pdo语句的好例子

function foo(&$var) {
    $variable1="test";
    $variable2="test";
    echo $var;
}
$string="UPDATE table SET column1=$variable1 WHERE column2=$variable2";
foo($string);

我也知道另一种实现此目的的方法。但这不是一个好方法

function test($Query) {
        $variable1="test";
        $variable2="test";

        $finalQuery = vsprintf($Query, array($variable1, $variable2));
        print_r($finalQuery);
    }
$Query = "UPDATE table SET column1='%s' WHERE column2='%s'";
test($Query);

3 个答案:

答案 0 :(得分:3)

假设您的示例中未按字面定义$variable1$variable2,(我从您的注释中假设“我需要使用我将创建的值正确填充$ Query在函数中”),我想说您的函数需要采用准备好的语句而不是字符串。

function foo(PDOStatement $statement) {
    // stuff happens that creates $variable1 and $variable2
    $statement->bindValue(1, $variable1);
    $statement->bindValue(2, $variable2);
    return $statement;
}

而不是定义$string,而是创建一个准备好的语句并将其传递给函数。

$statement = $pdo->prepare('UPDATE table SET column1=? WHERE column2=?');
foo($statement);

就您在问题的第一个代码块中尝试执行此操作的方式而言,存在一些问题。

传递带有预定义变量的字符串然后将其填充到函数中的唯一方法是首先定义带单引号的字符串。否则,用双引号引起来,PHP将在全局范围内查找$variable1$variable2,而不是查找它们,并且它们的未定义(空)值将被$string中的空字符串替换,您可以传递给该函数。

$string='UPDATE table SET column1=$variable1 WHERE column2=$variable2';

然后,在函数中,据我所知,您能够对那些预定义变量进行插值的唯一方法是将该字符串传递给eval

function foo(&$var) {
    $variable1="test";
    $variable2="test";
    eval('$var = "' . $var . '";');
    echo $var;
}

现在,此方法适用于此示例,但是 这是一个糟糕的主意

  • 当您像这样编写字符串时,您依赖于在函数内部定义的某些变量,而函数则取决于具有这些变量的输入。您将永远无法更改该功能。

  • 这取决于eval。使用eval是危险的。它允许将任何字符串作为PHP代码在您的系统上执行,并且您可能无法安全地限制该字符串的来源。

  • 如果这将用于执行SQL,那么这不是一个好方法,无论它是否是构建字符串的好方法,我已经说过没错您应该将值绑定到准备好的语句。

答案 1 :(得分:0)

您可以为此使用mysqli:

class Database {
  protected $con;
  public __construct(){
    $this->con=mysqli_connect("my_host","my_user","my_password","my_db");
    if (mysqli_connect_errno()) {   echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
  }

  public __destruct(){
    mysqli_close($this->con);
  }

  public query($sql){
    if (!mysqli_query($this->con,$sql)) {   die('Error: ' . mysqli_error($this->con)); };
  }

}

class Table extends Database {
  public function update($var, $var2){
    $var = mysqli_real_escape_string($con,$var);
    $var2 = mysqli_real_escape_string($con,$var2);
    $sql = "UPDATE table SET column1=$var1 WHERE column2=$var2";
    $this->query($sql);
  }
}

这样,您可以使用php mysqli_real_escape_string,这将帮助您防止SQL注入。

此外,您还可以使用“准备好的语句”选项。 只需更改,更新方法为:

public function update($var, $var2){
        $smtp = mysqli_prepare($this->con,"UPDATE table SET column1=? WHERE column2=?");
        mysqli_stmt_bind_param($smtp,'ss', $var,$var2);
        mysqli_stmt_execute($stmt);
}

答案 2 :(得分:0)

我相信您正在努力实现这一目标。

<?php
/* On update l'historique côté vets; ici on controle et on dit KESSKONFAI*/
    include('../Models/db_connect.php');
    $a = explode('-',$_GET['a']);
    $o = $_GET['o'];

    switch($a):
        case($a[1] === 'breed'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY breed DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY breed ASC";
                }
            break;
        case($a[1] === 'name'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY pet_name DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY pet_name ASC";
                }
            break;
        case($a[1] === 'color'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY colour DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY colour ASC";
                }
            break;
        case($a[1] === 'sex'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY sex DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY sex ASC";
                }
                break;
        case($a[1] === 'date'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY date_of_birth DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY date_of_birth ASC";
                }
            break;
        case($a[1] === 'chip'):
                if($a[0] === 'desc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY microchip_tatoo DESC";
                } else if ($a[0] === 'asc'){
                    $query = 
                    "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                    FROM patients
                    WHERE
                    owner_ID = :ID
                    ORDER BY microchip_tatoo ASC";
                }
            break;
        case($a[1] === 'hist'):
            if($a[0] === 'desc'){
                $query = 
                "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                FROM patients
                WHERE
                owner_ID = :ID
                ORDER BY history DESC";
            } else if ($a[0] === 'asc'){
                $query = 
                "SELECT pet_name, ID, breed, colour, sex, date_of_birth,microchip_tatoo, history
                FROM patients
                WHERE
                owner_ID = :ID
                ORDER BY history ASC";
            }
            break;
        default:
    endswitch;

    if(isset($query)){
        include('../Models/order_by_clients.php');
        $patients_rows = order_by($query,$o,$db);
    }
?>

功能:

<?php
    function order_by($query,$o,&$db){

        $query_params = array(':ID' => $o);

            try {
                $stmt = $db->prepare($query);
                $result = $stmt->execute($query_params);
                $patients_rows = $stmt -> fetchAll();
                for($i = 0;$i < count($patients_rows);$i++){
                    $patients_rows[$i]['history'] = "\n".strtr($patients_rows[$i]['history'],array("."=>".\r\r","\S:"=>" :\r","-"=>" - "));
                }
                include '../Views/order_by_clients.php';

            }catch(PDOException $ex){
                die("Failed to run query: " . $ex->getMessage());
            }
    }
?>

但是在功能中进行了切换