我有一个名为Master
的表,它有四列名为id
,A
,B
和C
。
当我更新表时,我需要修改用户选择的特定单列。例如,如果用户选择了列A
,则只会在数据库中更新A
个记录。如果用户选择C
,则只会更新C
条记录。
以下是我尝试过的代码,但它正在更新所有列。你能帮帮我吗?
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
UPDATE Master SET $column_name='$A'+20, $column_name='$B'+30, $column_name='$C'+50 WHERE user_id='$id'";
答案 0 :(得分:1)
虽然我的要求并不完全清楚,但我认为 将帮助您满足您的要求。这是一个动态的解决方案。如果不是,你可以澄清你的要求,我必须尽力解决它。谢谢你的询问。
* table schema is stakcoverflow
* table name is master_tbl
* fields name
id | a | b | c
<?php
$myHost = "localhost"; // use your real host name ex. myDomainName.com
$myUserName = "root"; // use your real login user name ex. myUserName
$myPassword = ""; // use your real login password ex. myPassword
$myDataBaseName = "stakcoverflow"; // use your real database name ex. myDataBaseName
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword", "$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
$sql="SELECT a,b,c,id FROM master_tbl ORDER BY id";
$affectedrowsno = 0;
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$column_name = $fieldinfo->name;
// Get field information for all fields
while ($row=mysqli_fetch_assoc($result))
{
$a = $row['a'];
$b = $row['b'];
$c = $row['c'];
$id = $row['id'];
$sql = "UPDATE master_tbl SET $column_name=$a+20, $column_name=$b+50, $column_name=$c+80 WHERE id=$id";
mysqli_query($con,$sql);
$affectedrowsno += count(mysqli_affected_rows($con));
}
}
echo "Affected rows = " . $affectedrowsno;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
答案 1 :(得分:-1)
您可以使用if语句:
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
if($column_name == 'A'){
UPDATE Master SET A='$A'+20 WHERE user_id='$id'";
} elseif($column_name == 'B'){
UPDATE Master SET B ='$B'+30 WHERE user_id='$id'";
}elseif($column_name == 'C'){
UPDATE Master SET C ='$C'+50 WHERE user_id='$id'";
}
}