您可以使用命名参数,这至少会使其更易于阅读,但您仍然需要将所有 26 个参数放入其中。使用 PDO,您将能够执行以下操作:
insert into tableName values (:id, :val1, :val2 ....)
它更容易阅读,并且对其他阅读代码的人来说更有意义。
然后,如果您决定使用 PDO 路径,您可以一举通过这样的数组传递所有参数:
$prepared->execute(array(':ID' => $ID, ':val1' => $var1, ':val2' => $var2, ...)))
编辑:我通常在我的代码中使用一些对象,如果你愿意,可以快速复制和粘贴:
类文件:
class mysqlDigitalcog
{
public $con;
private $userName = "yourDBName";
private $passWord = "yourPassword";
private $hostName = "mysql:host=localhost;dbname=example";
// Modify this to your connection
private $isDebug=false;
function __construct()
{
$this->con = new PDO ($this->hostName, $this->userName , $this->passWord);
$this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
function __destruct()
{
$this->con = null;
}
}
class myResult
{
private $mysqlAccess;
private $prepared;
public function __construct()
{
$this->mysqlAccess=new mysqlDigitalcog();
}
public function loadData1()
{
$sql="INSERT INTO W2_contact_us_FORM VALUES (:ID, :val1)";
$this->prepared = $this->mysqlAccess->con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$this->prepared->execute(array(':ID' => 1, ':val1' => 2))
}
public function loadData2($myArray)
{
$sql="INSERT INTO W2_contact_us_FORM VALUES (:ID, :val1)";
$this->prepared = $this->mysqlAccess->con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$this->prepared->execute($myArray)
}
}
实际页面代码:
$myResult=new myResult();
$array=array(":ID" => 3, ":val1" => 4);
$myResult->loadData1();
// Data loaded with 1, 2 as per function.
// or alternately
$myResult->loadData2($array);
// Data loaded with array contencts, here 3, 4
现在,我们有一个包含两个函数的对象,一个是所有输入都在函数本身内生成,另一个是值数组从外部传递给函数。