SQL not working to update MySQL database via PHP

Hello,

I was wondering if you’d be able to help with this, I am having trouble updating my database.

I only want to update the CarBrand and CarName columns for the relevant row (via IP match) when either of these columns is empty.

Please can you tell me if there are any errors with this syntax?

[php]
$sql = “UPDATE my_table SET
CASE
WHEN CarBrand = ‘’ THEN :carbrand
WHEN CarName = ‘’ THEN :carname
END
DateTime= :date,
Viewed = :viewed
WHERE IP = :ip”;

$stmt = $database->prepare($sql);
$stmt->bindParam(":carbrand", $CarBrand, PDO::PARAM_STR);
$stmt->bindParam(":carname", $CarName, PDO::PARAM_STR);
$stmt->bindParam(":date", $date, PDO::PARAM_STR);
$stmt->bindValue(":viewed", “1”, PDO::PARAM_INT);
$stmt->bindParam(":ip", $ip, PDO::PARAM_STR);
$stmt->execute();
[/php]

I would do it this way.

[php] $sql = "UPDATE my_table SET CarBrand = :carbrand, CarName = :CarName , DateTime= :date, Viewed = :viewed
WHERE IP = :ip and ((CarBrand IS NULL or CarBrand = ‘’) or (CarName IS NULL or CarName = ‘’)) ";[/php]

Here is the syntax example for a switch statement for MYSQL:
[php]
SELECT
CASE field
WHEN ‘value1’ THEN ‘output_value1’
WHEN ‘value2’ THEN ‘output_value2’
WHEN ‘value3’ THEN ‘output_value3’
END AS fieldAlias
FROM
table [/php]

You could use a prepared statement for this, but, I think I would recommend two separate queries, using php to determine which to actually use.

Sponsor our Newsletter | Privacy Policy | Terms of Service