Php PDO MySQL函数的数组
我尝试在PHP中使用PDO MySQL和execute命令。但我坚持在execute命令中使用数组,代码如下:Php PDO MySQL函数的数组,php,arrays,pdo,Php,Arrays,Pdo,我尝试在PHP中使用PDO MySQL和execute命令。但我坚持在execute命令中使用数组,代码如下: public static function join2ArAliasAndArValue($values=array(),$alias=array()){ $data = array(); for($i=0;$i<count($values);$i++){ $data[$alias[$i]] = $values[$i]; } r
public static function join2ArAliasAndArValue($values=array(),$alias=array()){
$data = array();
for($i=0;$i<count($values);$i++){
$data[$alias[$i]] = $values[$i];
}
return $data;
}
数据必须是这样的:
Array (
':id_val' => '01' ,
':name_val' => 'tatang',
':phone_val' => '0989989',
':address_val' => 'kemanggisan',
':idkey_val' => '100'
如何创建这样的数组,删除方括号并在每个数组值中添加逗号,请有人帮我
这里是我的函数addrecord:
public static function addRecordToTable($table,$fields=array(),$values=array(),$alias=array()){
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$sql = " INSERT INTO $table ";
$fields = implode("`, `", $fields);
$newalias = implode("', '", $alias);
$sql .= "(`$fields`) VALUES ('$newalias')";
$alias = explode(', ', $newalias);
$data = $data = Helpers::join2ArAliasAndArValue($values,$alias);
/** DEBUG */
Debug::debugInput('FIELDS',$fields);
Debug::debugInput('NEW-ALIAS',$newalias);
Debug::debugInput('SQL',$sql);
Debug::debugInput('ALIAS',$alias);
Debug::debugInput('DATA',$data);
$query = $database->prepare($sql);
$query->execute($data);
$output = $query->rowCount() == 1 ? true : false;
}
对于调试:
public static function debugInput($title,$data){
$action = is_array($data) ? true : false;
if($action){
print $title . " : <b>"; print_r($data); print "</b><br />";
return false;
}
print $title . " : <b>" . $data; print "</b><br />";
}
__这里是我的成功代码:
public static function addRecordToTable($table,$fields=array(),$values=array(),$alias=array()){
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$sql = " INSERT INTO $table ";
$fields = implode("`, `", $fields);
$newalias = implode(", ", $alias);
$sql .= "(`$fields`) VALUES ($newalias)";
$alias = explode(', ', $newalias);
$data = $data = Helpers::join2ArAliasAndArValue($values,$alias);
/** DEBUG */
Debug::debugInput('FIELDS',$fields);
Debug::debugInput('NEW-ALIAS',$newalias);
Debug::debugInput('SQL',$sql);
Debug::debugInput('ALIAS',$alias);
Debug::debugInput('DATA',$data);
$query = $database->prepare($sql);
$query->execute($data);
$output = $query->rowCount() == 1 ? true : false;
}
假函数:
所以,$newAlias是正确的,请参见代码中的注释,因为在表单中,必须将单引号插入到INSERT sql语句中
$alias使用不正确,请参见代码中的注释。所以,只需删除
$alias = explode(', ', $newalias);
因为您不需要将$alias内爆为$newalias,然后再将此内爆为新的$alias
因此,正确的功能:
编辑2:
我试图重构您的代码,以便让您了解如何将一些处理策略结合在一起。有关详细信息,请阅读代码注释。我推荐
使用异常处理,以便能够始终发现由失败的数据库操作引起的错误,而不仅仅是这些错误。如果你愿意,你可以看到我的一个老答案:
在构建复杂字符串(如sql语句)时使用sprintf,但不要滥用它们。
以下是我看到的addRecordToTable函数:
public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
// Use try-catch blocks for exception handling.
try {
$database = DatabaseFactory::getFactory()->getConnection();
/*
* Build your sql statement using sprintf()
* and placeholders (defined through "%s").
* See: http://php.net/manual/en/function.sprintf.php
*/
$sql = sprintf(
" INSERT INTO %s (`%s`) VALUES ('%s')"
, stripslashes(strtolower($table))
, implode("`, `", $fields)
, implode("', '", $alias)
);
// I corrected here also, because you had "$data = $data = ...".
$data = Helpers::join2ArAliasAndArValue($values, $alias);
$query = $database->prepare($sql);
// Added this validation.
if (!$query) {
throw new Exception('The SQL statement can not be prepared!');
}
$executed = $query->execute($data);
// Added this validation.
if (!$executed) {
throw new Exception('The PDO statement can not be executed!');
}
$output = $query->rowCount() == 1 ? true : false;
/*
* Corrected (e.g. added) here also, because you
* have to return the results, e.g. the $output.
*/
return $output;
} catch (PDOException $pdoException) {
echo '<pre>' . print_r($pdoException, true) . '</pre>';
exit();
} catch (Exception $exception) {
echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
}
@恩德雷伊这个怎么样:
public static function updateRecordToTable($table,$fields=array(),$values=array(),$alias=array(),$key=array(),$key_alias=array(),$key_values=array(),$and=true){
try{
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$data = Helpers::join4ArAliasAndArValue($values,$alias,$key_alias,$key_values);
$update = ""; #must be declare
for($i=0;$i<count($fields);$i++){
$update .= "`".$fields[$i]. "` = ".$alias[$i].", ";
}
$update = substr($update, 0,-2);
#Debug::debugInput('PUSH',$update);
if($and){
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
}
$where .= substr($where,0,-4);
}else{
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j];
}
}
#Debug::debugInput('WHERE',$where);
$sql = sprintf("UPDATE %s SET %s WHERE %s", $table,$update,$where);
$query = $database->prepare($sql);
/** DEBUG
Debug::debugInput('SQL',$sql);
Debug::debugInput('DATA',$data);
*/
if(!$query){
throw new Exception('The SQL statement can not be prepared!');
}
$execute = $query->execute($data);
if(!$execute){
throw new Exception('The PDO statement can not be executed!');
}
return $execute;
} catch (PDOException $pdoException) {
echo '<pre>' . print_r($pdoException, true) . '</pre>';
exit();
} catch (Exception $exception) {
echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
}
如何使用try-catch更新:
这是我的更新代码
更新:
您是否尝试将数组传递给PDO execute?发生了什么?您的输出看起来像是print\r函数的输出。真正的数组不应该包含任何方括号。@TomUdding是的,我使用print\r。如果json编码为{:id_val:01,:name_val:tatang,:phone_val:0989989,:address_val:kemanggisan,:idkey_val:100}您的确切问题是什么?因为我看不出有什么问题。您是否也可以添加PDO代码?@ikwijaya在将参数$values和$alias传递给Join2ArialAsAndArvalue函数之前,不要使用json_encode或print_r。将普通$values和$alias数组作为参数传递,并且仅在从join2ArAliasAndArValue返回的结果上应用json_encode或print_r。抱歉,但您的解决方案不好:-请查看我的答案,当然您不必接受它。我现在发布了我的答案。感谢您清理我的代码,$alias=explode',“,$newalias@ikwijaya不客气。我现在将编辑我的答案,因为我想向您展示一种构建sql语句的优雅方式。@ikwijaya抱歉,这花了很长时间,但我现在通过重新编辑我的初始答案发布了我的建议。祝您的项目好运。一些错误警告:PDOStatement::execute:SQLSTATE[42S22]:未找到列:1054未知列300'、“tukang sapu'、“100'、“kemanggisan”位于D:\myfiles\xampp\htdocs\am\application\core\Query.php的第87行=>只需删除“%s”中的单引号并内爆“,”,$alias,因为数据未真正存储到数据库。感谢新的代码实现。这是很棒的代码。非常感谢。@ikwijaya我想现在可以用了。还是有关于警告码的问题?我也感谢你。哦,不要忘记:在准备sql语句时使用BindValuer或bindParam函数,而不是将绑定(例如输入参数数组)作为参数传递给PDOStatement::execute。这样可以传递插入值的正确数据类型。见我的编辑3。我刚刚在你的答案中添加了一些东西。我编辑了它。我不知道,如果你能看到的话。我必须在大约5分钟内去,所以看看它,并随时问我,即使我不在线。
public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
//...
$sql = " INSERT INTO $table ";
$fields = implode("`, `", $fields);
$newalias = implode("', '", $alias);
$sql .= "(`$fields`) VALUES ('$newalias')";
$data = $data = Helpers::join2ArAliasAndArValue($values, $alias);
//...
}
public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
// Use try-catch blocks for exception handling.
try {
$database = DatabaseFactory::getFactory()->getConnection();
/*
* Build your sql statement using sprintf()
* and placeholders (defined through "%s").
* See: http://php.net/manual/en/function.sprintf.php
*/
$sql = sprintf(
" INSERT INTO %s (`%s`) VALUES ('%s')"
, stripslashes(strtolower($table))
, implode("`, `", $fields)
, implode("', '", $alias)
);
// I corrected here also, because you had "$data = $data = ...".
$data = Helpers::join2ArAliasAndArValue($values, $alias);
$query = $database->prepare($sql);
// Added this validation.
if (!$query) {
throw new Exception('The SQL statement can not be prepared!');
}
$executed = $query->execute($data);
// Added this validation.
if (!$executed) {
throw new Exception('The PDO statement can not be executed!');
}
$output = $query->rowCount() == 1 ? true : false;
/*
* Corrected (e.g. added) here also, because you
* have to return the results, e.g. the $output.
*/
return $output;
} catch (PDOException $pdoException) {
echo '<pre>' . print_r($pdoException, true) . '</pre>';
exit();
} catch (Exception $exception) {
echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
}
//...
$sql = 'INSERT INTO demo_table (id, name) VALUES (:id, :name)';
$statement = $connection->prepare($sql);
if (!$statement) {
throw new Exception('The SQL statement can not be prepared!');
}
// Integer binding ":id".
$statement->bindValue(':id', $id, $this->getInputParameterDataType($id));
// String binding ":name".
$statement->bindValue(':name', $name, $this->getInputParameterDataType($name));
//...
function getInputParameterDataType($value) {
$dataType = PDO::PARAM_STR;
if (is_int($value)) {
$dataType = PDO::PARAM_INT;
} elseif (is_bool($value)) {
$dataType = PDO::PARAM_BOOL;
}
return $dataType;
}
public static function getAllDataFromTableWithWhere($table,$fields=array(),$key=array(),$key_values=array(),$key_alias=array(),$is=true,$and=true,$orderby){
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$fields = implode("`, `", $fields);
#Debug::debugInput('FIELDS',$fields);
if($is){
$sql = "SELECT `$fields` FROM $table WHERE "; #`$key` = ':key_id' ORDER BY `$orderby` ASC";
if($and){
for($j=0;$j<count($key);$j++){
$sql .= "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
}
$sql = substr($sql,0,-4);
}else{
for($j=0;$j<count($key);$j++){
$sql .= "`".$key[$j]. "` = ".$key_alias[$j]." ";
}
$sql = substr($sql,0,-1);
}
}else{
$sql = "SELECT `$fields` FROM $table WHERE "; #`$key` LIKE `:key_id` ORDER BY `$orderby` ASC";
if($and){
for($j=0;$j<count($key);$j++){
$sql .= "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
}
$sql = substr($sql,0,-4);
}else{
for($j=0;$j<count($key);$j++){
$sql .= "`".$key[$j]. "` = ".$key_alias[$j]." ";
}
$sql = substr($sql,0,-1);
}
}
$sql .= " ORDER BY $orderby";
$data = Helpers::join2ArAliasAndArValue($key_values,$key_alias);
#Debug::debugInput('SQL',$sql);
#Debug::debugInput('DATA',$data);
$query = $database->prepare($sql);
$query->execute(array(':idkey_val' => $key_values[0]));
return $query->fetchAll();
}
public static function updateRecordToTable($table,$fields=array(),$values=array(),$alias=array(),$key=array(),$key_alias=array(),$key_values=array(),$and=true){
try{
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$data = Helpers::join4ArAliasAndArValue($values,$alias,$key_alias,$key_values);
$update = ""; #must be declare
for($i=0;$i<count($fields);$i++){
$update .= "`".$fields[$i]. "` = ".$alias[$i].", ";
}
$update = substr($update, 0,-2);
Debug::debugInput('PUSH',$update);
if($and){
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
}
$where .= substr($where,0,-4);
}else{
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j];
}
}
Debug::debugInput('WHERE',$where);
$sql = sprintf(
"UPDATE %s SET %s WHERE %s", $table,$update,$where
);
$query = $database->prepare($sql);
/** DEBUG */
Debug::debugInput('SQL',$sql);
Debug::debugInput('DATA',$data);
if(!$query){
throw new Exception('The SQL statement can not be prepared!');
}
$execute = $query->execute($data);
if(!$execute){
throw new Exception('The PDO statement can not be executed!');
}
return $execute;
} catch (PDOException $pdoException) {
echo '<pre>' . print_r($pdoException, true) . '</pre>';
exit();
} catch (Exception $exception) {
echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
}
public static function updateRecordToTable($table,$fields=array(),$values=array(),$alias=array(),$key=array(),$key_alias=array(),$key_values=array(),$and=true){
try{
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$data = Helpers::join4ArAliasAndArValue($values,$alias,$key_alias,$key_values);
$update = ""; #must be declare
for($i=0;$i<count($fields);$i++){
$update .= "`".$fields[$i]. "` = ".$alias[$i].", ";
}
$update = substr($update, 0,-2);
#Debug::debugInput('PUSH',$update);
if($and){
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
}
$where .= substr($where,0,-4);
}else{
for($j=0;$j<count($key);$j++){
$where = "`".$key[$j]. "` = ".$key_alias[$j];
}
}
#Debug::debugInput('WHERE',$where);
$sql = sprintf("UPDATE %s SET %s WHERE %s", $table,$update,$where);
$query = $database->prepare($sql);
/** DEBUG
Debug::debugInput('SQL',$sql);
Debug::debugInput('DATA',$data);
*/
if(!$query){
throw new Exception('The SQL statement can not be prepared!');
}
$execute = $query->execute($data);
if(!$execute){
throw new Exception('The PDO statement can not be executed!');
}
return $execute;
} catch (PDOException $pdoException) {
echo '<pre>' . print_r($pdoException, true) . '</pre>';
exit();
} catch (Exception $exception) {
echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
}