PDO bindValue适用于其他输入,为什么不是这个?
题
我正在构建一个表单,用户可以在其中更新书籍的属性。有一个动态生成的HTML表单,用户可以为"标题","作者"和"描述"等内容输入新值,看起来像这样:
echo "<form id=changerform name=changerform action=updatesubmit.php method=post>";
echo "<span id=titlebox>Title: <input class=attributefield style='border:none' type=text size=100 id=Title value='".$item['Title']."' />Change This?</span> <br>";
echo "<span id=authorbox>Author: <input class=attributefield style='border:none' type=text id=Author value='".$item['Author']."' />Change This?</span><br>";
echo "<span id=description>Description: <textarea class=attributefield style='border:none' rows=9 cols=100 name=Description id=Description >".$item['Description']."</textarea></span>";
echo "<input type='hidden' id='bookidfield' name='bookidfield' value = '".$toChange."' />";
这个表单由一些php处理,看起来像这样:
while($nowfield = current($_POST)){
$col = key($_POST);
switch($col){
case 'Title':
$qstring = 'UPDATE Mainbooks SET Title = :slug WHERE ItemID LIKE :bookid;';
break;
case 'Author':
$qstring = 'UPDATE Mainbooks SET Author = :slug WHERE ItemID LIKE :bookid;';
break;
case 'Description':
$qstring = "UPDATE Mainbooks SET Description = :slug WHERE ItemID LIKE :bookid;";
break;
default:
echo "Invalid input";
break;
}//end switch
$upquery = $safelink->prepare($qstring);
$upquery->bindValue(':slug', $nowfield, PDO::PARAM_STR);
$upquery->bindValue(':bookid', $_POST['bookidfield'], PDO::PARAM_INT);
$upquery->execute();
next($_POST);
} //end while
我将其组织为switch语句,因为表单中的代码只传递在post中更改的字段('bookidfield'输入除外,该输入具有其中每个项目的唯一键。)与交换机,只有必要的查询运行。
"标题"和"作者"字段工作正常;它们会毫无问题地更新到新值。但是,"描述"字段始终更新为"bookidfield"的值。'如果我进去并手动将':bookid'参数更改为我想要的书的id,我可以修复它。
如果我 var_dump(_$POST)
它似乎通过正确的关键值,就像这样:
array(4) { ["Title"]=> string(22) "Gross Boogers and Such" ["Author"]=> string(14) "Franny Panties" ["Description"]=> string(55) "This is the value I want to change the description to!!" ["bookidfield"]=> string(3) "184" }
但是在我的SQL表中,它会将book184的标题更改为"Gross Boogers And Such",作者更改为"Franny内裤",但它会将描述更改为"184。"这与我使用bindValue()有关,对吧?还是跟我的循环有关?它是如何命名的形式?我看它太久了,看不到它是什么。
感谢Stackoverflow,你们很棒。
解决方案
你的问题是,当$col与标题,作者或描述不同时,换句话说,当开关执行默认情况时,你正在执行$nowfield=184的上一个查询。不得执行查询。
当switch执行默认情况时,您必须"跳转"到下一个值,跳过查询执行。
default:
echo "Invalid input";
next($_POST);
continue 2;
break;
其他提示
你的HTML因 资料描述 <textarea>
.你有。..
<textarea ... name=Description id=Description />".$item['Description']."</textarea>
<!-- ^ there's your problem -->
它应该在哪里
<textarea ... name=Description id=Description>".$item['Description']."</textarea>
正如我在评论中提到的,你生成HTML的方式必然会导致问题。我建议你采取这种方法。..
// leave the PHP context
?>
<form id="changerform" action="updatesubmit.php" method="post">
<span id="titlebox">
Title:
<input class="attributefield" type="text" id="Title" value="<?= htmlspecialchars($item['Title']) ?>">
Change This?
</span>
<!-- you get the idea -->
</form>
不隶属于 StackOverflow