Update Multiple Rows in one PHP

2019-02-20 22:21发布

问题:

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

回答1:

Why not use the metal name as your key?

$update="UPDATE metals SET value = '".$gold."' WHERE type = 'gold'";

And you really need to switch to prepared statements. You're wide open to SQL injection



回答2:

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.