我有这个PHP代码,它从数据库中选择行并将数据放在表单字段中:
$global_sql2="SELECT name, field, value FROM global_settings";
$global_rs2=mysql_query($global_sql2,$conn) or die(mysql_error());
while($global_result2=mysql_fetch_assoc($global_rs2))
{
echo '<tr>
<td><strong>'.$global_result2["name"].'</strong></td>
<td><input type="text" name="'.$global_result2["field"].'" size="50" value="'.$global_result2["value"].'" /></td>
</tr>';
}
然后在提交页面上显示这个PHP代码:
$global_sql3="SELECT name, field, value FROM global_settings";
$global_rs3=mysql_query($global_sql3,$conn) or die(mysql_error());
while($global_result3=mysql_fetch_assoc($global_rs3))
{
if($_POST[$global_result3["field"]] != $global_result3["value"])
{
$sql="UPDATE global_settings set value = '".$_POST[$global_result3["field"]]."' where field = '".$global_result3["field"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
echo '<h3><font color="#FF0000">'.$global_result3["name"].'</font> Successfully Updated to <font color="#FF0000">'.$_POST[$global_result3["field"]].'</font></h3>';
}
}
我希望能够更新多个字段 - 以上只适用于数据库中的值列,但我希望能够做5列
我该怎么做?
P.S:我不担心SQL注入,因为这段代码不公开
答案 0 :(得分:2)
您正在寻找的是使用逗号分隔的字段名称设置列:
UPDATE `tableName` SET `field1` = 'value', `field2` = 'value', `field3` = 'value' WHERE `field` = 'fieldname';
如果要在1个查询中更新具有不同值的多个行,则需要使用case语句。快速谷歌搜索返回了一个非常直接的教程here
UPDATE mytable
SET field1 = CASE mainField
WHEN mainFieldName1 THEN 'value'
WHEN mainFieldName2 THEN 'value'
WHEN mainFieldName3 THEN 'value'
END,
field2 = CASE mainField
WHEN mainFieldName1 THEN 'New Title 1'
WHEN mainFieldName2 THEN 'New Title 2'
WHEN mainFieldName3 THEN 'New Title 3'
END
WHERE mainField IN (mainFieldName1,mainFieldName2,mainFieldName3)
答案 1 :(得分:0)
即使您不关心SQL注入,您也应该学习最佳实践,更不用说PDO具有更好,更清晰的OO语法。您也可以使用单个页面而不是单独的PHP文件。
将SQL,PHP和HTML混合在一起非常容易在眼睛上并且不能很好地保持良好状态。我写了一些小辅助函数来提高可重用性和可读性。
<?php
$dbh=false;
//Connect to your DB with PDO, only create the connection once
function getDbConnection() {
global $dbh;
$dbh = $dbh ? $dbh : new PDO('mysql:host=127.0.0.1;dbname=myDb', 'root', '');
return $dbh;
}
function getSettings(){
return getDbConnection()->query('SELECT * from global_settings');
}
function updateSettings(){
foreach($_POST['settings'] as $key => $value){
//Use a prepared statement with named parameters
$query = getDbConnection()->prepare('UPDATE global_settings set value=:value WHERE field=:field');
//Use named params to mitigate security issues
$query->bindParam(':value', $value);
$query->bindParam(':field', $key);
$query->execute();
}
}
// Has the form been submitted?
if(isset($_POST['settings']))
updateSettings();
?>
<form action="" method="post">
<table>
<?php foreach(getSettings() as $setting): ?>
<tr>
<td>
<label><?= $setting['field'] ?></label>
<input type="text" name="settings[<?= $setting['field'] ?>]" size="50" value="<?= $setting['value'] ?>" />
</td>
</tr>
<?php endforeach; ?>
</table>
<input type='submit' />
</form>
这基于以下数据库架构:
你会得到一个这样的表格:
这里有一个很好的PDO启动器:http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/