gpt4 book ai didi

php - 如何使用 php 在更新查询中更新具有多列的特定单列?

转载 作者:行者123 更新时间:2023-11-30 22:06:34 24 4
gpt4 key购买 nike

我有一个名为 Master 的表,它有四列分别称为 idABC

当我更新表格时,我需要修改用户选择的特定单个列。例如,如果用户选择了 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'";

最佳答案

Although your requirement is not fully clear to me so then i think it will be helped you to meet your requirement. It is a dynamic solution. If it's not you can clarify your requirement i will must be try my best to resolve it. Thanks for asking.

* 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);

?>

关于php - 如何使用 php 在更新查询中更新具有多列的特定单列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41519127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com