0

我正在开发一个应用程序,它根据从另一个表中选择的值更新表中的数据。我已经搜索了网络,并尝试修改一些示例以满足我的需要,但仍然无法正常工作。

下面是我的一些代码:

$sync_2 = "
  select pin,ddt_1
  from purchases
  where (amount_to_repay-amount_repaid)>0
    and status like 'U%'
    and counter=1
";
$sync_2_res = mysqli_query($link, $sync_2);
$row = mysqli_fetch_assoc($sync_2_res);
$data = mysqli_num_rows($sync_2_res);

$i;
for ($i = 0; $i <= $data; $i++) {
  $pin = $row['pin'];
  $ddt = $row['ddt_1'];
  $sql = "
    update deductions
    set amount = '$ddt_1'
    where pin = '$pin';
  $result = mysqli_query($link,$sql);
}

什么都没有填充。我必须更改循环的类型吗?

4

4 回答 4

2

试试这个代码,它应该在一个查询中完成整个操作:

$query = "
  UPDATE `deductions` `d`
  JOIN `purchases` `p` ON `p`.`pin` = `d`.`pin`
  SET `d`.`amount` = `p`.`ddt_1`
  WHERE
    (`p`.`amount_to_repay` - `p`.`amount_repaid`) > 0
    AND `p`.`status` LIKE 'U%'
    AND `p`.`counter` = 1
";
$result = mysqli_query($link, $query);
于 2012-04-04T12:55:16.120 回答
1

正如您所给出的,您的变量在 sql 语句中将 $ddt_1 更改为 $ddt 可能存在问题

 for($i=0;$i<=$data;$i++)

 {
 $pin=$row['pin'];
 $ddt=$row['ddt_1];
 $sql="update
  deductions
 set amount='$ddt'
 where pin='$pin';
$result=mysqli_query($link,$sql);
    }
于 2012-04-04T12:46:47.420 回答
0

改进的 PHP 示例

$mysqli = new mysqli ( "localhost", "root", "", "test" );
$sql  = "SELECT pin , ddt_1  from purchases WHERE  amount_to_repay-amount_repaid  >  0  AND  status like 'U%' AND counter = 1";
$sql2 = "update deductions  set amount = '%s'  where pin = '%s'; ";
$result = $mysqli->query($sql);
$row = null ;
while ($row = $result->fetch_assoc())
{
     $mysqli->query(sprintf ( $sql, $row ['pin'], $row ['ddt_1'] ));
}

旧帖子

代替

 $ddt=$row['ddt_1];

 $ddt=$row['ddt_1'];

代替

set amount='$ddt_1'

set amount='$ddt'

我希望这有帮助

谢谢

:)

于 2012-04-04T12:48:50.160 回答
0

首先要注意的是mysqli_fetch_assoc()只获取一行,即光标所在的行。然后它将光标移动一行。当游标到达数据末尾时mysqli_fetch_assoc()返回NULL

因此,要遍历一组结果,人们通常使用while 循环,因为这是最简洁的:

$sync_2_res = mysqli_query($link, $sync_2);

if($sync_2_res == null) {
    echo "The sync2 query failed: " . mysqli_error($link);
    exit();
}

while($row = mysqli_fetch_assoc($result) {
    // do something with $row
}

检查查询是否有效并返回结果而不是 FALSE 也是一个好主意。

接下来,我认为第二个查询中有一个错字:$dtt_1应该是$dtt,您真的确定该amount字段应该设置为字符串吗?

无论如何,这就是我将如何重写您的代码:

$sync_2= "select pin,ddt_1 from purchases "
    . "where (amount_to_repay-amount_repaid)>0 "
    . "and status like 'U%' and counter=1";

$sync_2_res=mysqli_query($link,$sync_2);

// check the query worked
if(!$sync_2_res) {
    echo "The sync2 query failed: " . mysqli_error($link);
    exit();
}

while($row = mysqli_fetch_assoc($result) {
    // do something with $row
    $pin=$row['pin'];
    $ddt=$row['ddt_1'];
    // note change from $ddt_1 to $dtt
    $sql="update deductions set amount='$ddt' where pin='$pin';";

    $result=mysqli_query($link,$sql);
    // check query worked
   if(!$result) {
      echo "The 2nd query failed: " . mysqli_error($link);
   }
}
于 2012-04-04T13:17:32.567 回答