I want to update a table value to either 1 of 2 values.
The selected value has 2 possible choices I ride a bike or I fly an airplane.
If the entered value is I ride a bike then the database value should be set as 1 , if it’s I fly an airplane then the value should be set at 2.
This way When I display/view the table, either an image of a bike (called 1.png) or a plane (called 2.png) will be displayed , based on what the value of transport is set as.
// get the passed variables from the web form
$id=$_POST['id'];
$pid = $_POST['pid'];
$transport=$_POST['transport'];
// update data in mysql database
$sql = "UPDATE survey SET pid=?, transport=? WHERE id=?";
$stmt= $con->prepare($sql);
$stmt->bind_param("ssi", $pid, $transport, $id);
$stmt->execute();
The above code currently works but displayed in the table is the text of ride bike or fly airplane
I prefer the simple image
So I was thinking something like using strlen, ride bike has 15 characters,or airplane has 18
$sql = "UPDATE survey SET pid=?,if (strlen(['transport']) == 18){set '2';}else{set '1';} ,WHERE id=?";
but it doesn’t work and I have no idea because this is just a hobby.
2
Answers
You have to put the
IF
in the value expression. SQL is not a procedural language.You’re also missing the column to assign to.
But hard-coding lengths like this seems error-prone — what if you had two values with the same length. Compare with the actual string.
This also generalizes better when you have more than 2 choices, you can just add more
WHEN
clauses.You can also use the
FIELD()
function:You could do this in PHP.
Or, you could do this:
Get really fancy