PHP更新到MySQL与数组不更新 [英] php update to mysql with array not updating
问题描述
我有一个应该更新一行的功能,日志中没有任何错误.从我看来,它应该可以正常工作.我从更新用户功能中获取了该功能,并尝试模仿该功能以实现新功能.
I have a function that should be updating a row, no errors what so ever in the logs. From what I see it should be working. I took the function from a update user function and tried to mimic it for the new feature.
这是向其发布数据数组.
Here is the data array posting to it.
$data = array('id' => $vid, 'name' => $vname, 'logo' => $vlogo, 'info' => $vinfo, 'site' => $vsite, 'est' => $vest);
该帖子正常运行,我在updatecompany页面上进行了转储.所以他们确实被设置了.我认为可能与功能有关.任何见识都将是美好的!
The post works, I am doing a dump on the updatecompany page. So they do get set. I think it may be with the function. Any insight would be wonderful!
public static function updateCompany($toUpdate = array(), $company = null){
self::construct();
if( is_array($toUpdate) && !isset($toUpdate['id']) ){
if($company == null){
echo "No company ID set!";
}
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "`$k` = :$k, ";
}
$sql = self::$dbh->prepare("UPDATE companys SET {$columns} WHERE `id` = :id");
$sql->bindValue(":id", $company);
foreach($toUpdate as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
$sql->execute();
}else{
return false;
}
}
$vid = $_POST["idnum"];
$vname = $_POST["name"];
$vlogo = $_POST["logo"];
$vinfo = $_POST["info"];
$vsite = $_POST["site"];
$vest = $_POST["est"];
推荐答案
您的更新SQL无效,因为更新值集中有逗号.
Your update SQL could not work because you have comma in update value set.
请参见,您在不加考虑的情况下附加了逗号:
See, you attached comma without any consideration:
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "`$k` = :$k, ";
}
然后,最终的SQL将如下所示:
Then the final SQL will look something like this:
UPDATE companys SET `name`=:name, `logo`=:logo, WHERE `id`=:id
您是否注意到WHERE
之前的逗号?它不应该在那里!
Do you notice the comma just before WHERE
? it should not be there!
因此,您应该更新如下代码:
So you should update the code like following:
$columns = "";
foreach($toUpdate as $k => $v){
if ($columns != "") $columns .= ",";
$columns .= "`$k` = :$k ";
}
这应该正常工作.
这篇关于PHP更新到MySQL与数组不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!