duanjianhe1388 2013-11-14 01:41 采纳率: 100%
浏览 21

在一个PHP中更新多行

I have three rows with three columns in one table

id    type       value
1     gold       1000.00
2     silver     32.21
3     platinum   1500.00

I have a form on my page with three inputs to fill in the updated values and am using ajax to send those values to update_values.php

The code below works, but I am curious as to whether there is a more efficient / proper way of doing this. Thanks in advance for the knowledge-boost!

PHP

//Pull data from settings update
$gold=$_POST['gold'];
$silver=$_POST['silver'];
$plat=$_POST['plat'];

//Configure and Connect to the Database
include_once('creds.php');
include_once('db_conn.php');
mysqli_select_db($con,"metals");

//Insert Data into table & return status
$select="Select * FROM metals";
$query=mysqli_query($con,$select);

$update="UPDATE metals SET value = '".$gold."' WHERE id = 1";
$update2="UPDATE metals SET value = '".$silver."' WHERE id = 2";
$update3="UPDATE metals SET value = '".$plat."' WHERE id = 3";

$query=mysqli_query($con,$update);
$query2=mysqli_query($con,$update2);
$query3=mysqli_query($con,$update3);
if($query && $query2 && $query3){
   echo "Updated!";
}
else{ echo "An error occurred!"; };
mysqli_close($con);
  • 写回答

2条回答 默认 最新

  • douweiduo7526 2013-11-14 01:53
    关注

    You could use a CASE clause like this:

    $query = "UPDATE metals SET value = CASE id WHEN 1 THEN $gold  WHEN 2 THEN $silver WHEN 3 THEN $plat END";
    

    This seems a bit of overkill for just three rows, though.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100