SQL IF STATEMENT with PHP variable Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of SQL IF STATEMENT with PHP variable without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to make a single query with SQL conditions like the above:

Let’s say first that we have the PHP variable $reco that will let us update the data when we want:

mysql_query("
INSERT INTO app_table (views, average)
VALUES
(
IF($reco = 'yes', '$views', views),
IF($reco = 'yes', '$aver', average)
)
ON DUPLICATE KEY UPDATE
views = IF($reco = 'yes', $views, views),
average = IF($reco = 'yes', $aver, average)
");

The problem is that $reco doesn’t works as I want inside the query but a column of table will work, so how can make it work with a PHP variable?

For example if I had reco inside the table would work like this:

Notice that I have the $reco in php variable not inside the table.

mysql_query("
INSERT INTO app_table (views, average)
VALUES
(
IF(reco = 'yes', '$views', views),
IF(reco = 'yes', '$aver', average)
)
ON DUPLICATE KEY UPDATE
views = IF(reco = 'yes', $views, views),
average = IF(reco = 'yes', $aver, average)
");

Answer

Well, if it’s kind of a proof of the principle, and you still want to do it on the SQL side:

$query = "... IF('$reco' = 'yes', '$views' ...";

Note the quotes around $reco. So, if $reco were ‘yes’ the query would be interpreted as ... IF ('yes' = 'yes', 'some_value' ...

We are here to answer your question about SQL IF STATEMENT with PHP variable - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji