mysql query with if and else statement - php

I need mysql query that will :
IF (result=win){SELECT dobitak} else if (result=half_win) {SELECT dobitak/2} else if (half_lost) {SELECT stake/2} else{0};
FROM matches
WHERE id=$id
but i dont know whats the best solution to write query like this.

select case when result ='win' then dobitak
when result = 'half_win' then dobitak/2
when result = 'half_lost' then stake/2
else 0
end as result
FROM matches
WHERE id=$id

I think you can do what you want with a case statement:
select (case when result = win then dobitak
when result = half_win then dobitak/2
when half_lost then stake / 2
else 0
end)
from matches
where id = $id;

Related

unknown error/data in LIKE query Mysql

i have this code
$opslaglimit = 5;
$fag = "dansk";
$fagquery = "%".ucfirst($fag)."%";
$fagopslag = $db->prepare("
SELECT
*,
teacher_opslag.id as mainid,
teacher_opslag.created AS opslagcreated,
teacher_opslag.subject AS opslagsubject,
teacher_opslag.deleted AS maindeleted
FROM
teacher_opslag
WHERE
teacher_opslag.subject LIKE ?
ORDER BY
teacher_opslag.id DESC
LIMIT
$opslaglimit
");
$fagopslag->bind_param("s", $fagquery);
$fagopslag->execute();
$fagresult = $fagopslag->get_result();
$ensuranced = $fagresult->num_rows;
The query should select all data where dansk is present from the table. one of my rows might look like this Dansk_Engelsk_Svensk. The num_rows returns 0.
It is the first time i use LIKE in a WHERE clause. I dont know why it returns 0 when i have 3 matching rows in the db.
please help, thanks

SQL query results returned, even if exact match not found

I hope this question isn't redundant. What I am trying to accomplish is have a user select a bunch of checkboxes on a page and return the closest matching records if there are no matching rows. For example:
A person checks off [x]Apples [x]Oranges [x]Pears [x]Bananas
But the table looks like this:
Apples Oranges Pears Bananas
1 1 1 null
1 1 null 1
1 1 null null
(Obviously I missed the id column here, but you get the point I think.) So, the desired result is to have those three rows still be returned in order of most matches, so pretty much the order they are in now. I'm just not sure what the best approach to take on something like this. I've considered a full text search, the levenshtein function, but I really like the idea of returning the exact match if it exists. No need for you to go at length with code if not needed. I'm just hoping to be sent in the right direction. I HAVE seen other questions sort of like this, but I still am unsure about which way to go.
Thanks!
Write a query that adds up the number of columns that matched, and sorts the rows by this total. E.g.
SELECT *
FROM mytable
ORDER BY COALESCE(Apples, 0) = $apples + COALESCE(Oranges, 0) = $oranges + ... DESC
It's easy to sort by a score...
SELECT fb.ID, fb.Apples, fb.Oranges, fb.Pears, fb.Bananas
FROM FruitBasket fb
ORDER BY
CASE WHEN #Apples = fb.Apples THEN 1 ELSE 0 END
+ CASE WHEN #Oranges = fb.Oranges THEN 1 ELSE 0 END
+ CASE WHEN #Pears = fb.Pears THEN 1 ELSE 0 END
+ CASE WHEN #Bananas = fb.Bananas THEN 1 ELSE 0 END
DESC, ID
However, this leads to a table-scan (even with TOP). The last record may be a better match than the records found so far, so every record must be read.
You could consider a tagging system, like this
Content --< ContentTag >-- Tag
Which would be queried this way:
SELECT ContentID
FROM ContentTag
WHERE TagID in (334, 338, 342)
GROUP BY ContentID
ORDER BY COUNT(DISTINCT TagID) desc
An index on ContentTag.TagId would be used by this query.
This is fairly simple, but you can just use IFNULL() (MySQL, or your DB's equivalent) to return a sum of matches and use that in your ORDER BY
// columns and weighting score
$types = array("oranges"=>1, "apples"=>1, "bananas"=>1, "pears"=>1);
$where = array();
// loop through the columns
foreach ($types as $key=>&$weight){
// if there is a match in $_REQUEST at it to $where and increase the weight
if (isset($_REQUEST[$key])){
$where[] = $key . " = 1";
$weight = 2;
}
}
// build the WHERE clause
$where_str = (count($where)>0)? "WHERE " . implode(" OR ", $where) : "";
// build the SQL - non-null matches from the WHERE will be weighted higher
$sql = "SELECT apples, oranges, pears, bananas, ";
foreach ($types as $key=>$weight){
$sql .= "IFNULL({$key}, 0, {$weight}) + ";
}
$sql .= "0 AS score FROM `table` {$where_str} ORDER BY score DESC";
Assuming that "oranges" and "apples" are selection, your SQL will be:
SELECT apples, oranges, pears, bananas,
IFNULL(apples, 0, 2) + IFNULL(oranges, 0, 2) + IFNULL(pears, 0, 1) + IFNULL(bananas, 0, 1) + 0 AS score
FROM `table`
WHERE oranges = 1 OR apples = 1
ORDER BY score DESC
Order descending by the sum of checkbox/data matches
SELECT * FROM table
ORDER BY (COALESE(Apple,0) * #apple) + (COALESE(Orange,0) * #orange) ..... DESC
where #apple / #orange represents users selection: 1 = checked, 0 = unchecked

How can you use CASE Statements to assign values to matches in your query?

Let's say your running a query and you have a lot of different user inputs that may not find an exact match. Now would it be possible to do something like the following?
$query = "SELECT *,
CASE matchingValues
WHEN $field1 LIKE '$a' THEN value = '1' ELSE value = '0'
WHEN $field2 LIKE '$b' THEN value = '1' ELSE value = '0'
WHEN $field3 LIKE '$c' THEN value = '1' ELSE value = '0'
WHEN $field4 LIKE '$d' THEN value = '1' ELSE value = '0'
WHEN $field5 LIKE '$e' THEN value = '1' ELSE value = '0'
END AS score
FROM . $usertable
WHERE
$field1 LIKE '$a' AND
$field2 LIKE '$b' AND
$field3 LIKE '$c' AND
$field4 LIKE '$d' AND
$field5 LIKE '$d'
ORDER BY score DESC";
if($result = mysql_query($query)) {
if(mysql_num-rows($result)==NULL) {
echo 'No Results Found';
}else{
....
Yes this is possible, though you would do it without the WHERE clause, and you would want to add up all the inputs instead of using a CASE to get the total score. Since each LIKE statement returns a boolean 1 or 0, you can just add them up to find out how many matches you have. A HAVING clause then limits to rows returned with a score > 0, if you want to return only those that actually matched.
SELECT *,
(($field1 LIKE '$a') +
($field2 LIKE '$b') +
($field3 LIKE '$c') +
($field4 LIKE '$d') +
($field5 LIKE '$e')) AS score
FROM . $usertable
HAVING score > 0
ORDER BY score DESC";
We assume you have already added % wildcards to the LIKE variables, and that they have been properly escaped prior to use in your query.
However, while you can do it this way (a poor-man's full-text search), MySQL offers the possibility of creating a full text index across multiple columns on MyISAM tables.
Update: To artificially weight them...
If you have a need to weight them, use CASE statements and put in higher numbers for the top few:
SELECT *,
(CASE WHEN ($field1 LIKE '$a') THEN 5 ELSE 0 END +
CASE WHEN ($field2 LIKE '$b') THEN 4 ELSE 0 END +
CASE WHEN ($field3 LIKE '$c') THEN 3 ELSE 0 END +
CASE WHEN ($field4 LIKE '$d') THEN 2 ELSE 0 END +
CASE WHEN ($field5 LIKE '$e') THEN 1 ELSE 0 END) AS score
FROM . $usertable
HAVING score > 0
ORDER BY score DESC";
To just enforce that the first one match, put it in your WHERE clause.
SELECT *,
(($field1 LIKE '$a') +
($field2 LIKE '$b') +
($field3 LIKE '$c') +
($field4 LIKE '$d') +
($field5 LIKE '$e')) AS score
FROM . $usertable
WHERE $field1 LIKE '$a'
HAVING score > 0
ORDER BY score DESC";
Again, to be clear - a very closely related functionality is already built-in and optimized in MySQL's full text indexing and the MATCH keyword.

Output in HTML page a mySQL query with PHP

I have a query like this
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND
jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM
jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR
jr_othersoftware LIKE \'%sony%\'";
I want to output results in HTML pages. I run a Joomla based site.
How can I do that?
Sorry but I'm not so skilled in PHP, I'm learning.
Expected result in HTML page (frontend), example:
SONY Products: 105
Thanks in advance to all!
In your case, use it like this:
$sql = "SELECT SUM(CASE WHEN jr_softwarecheck LIKE \'%sony\' AND jr_othersoftware LIKE \'%sony%\' THEN 2 ELSE 1 END) AS totalcount FROM jos_jreviews_content WHERE jr_softwarecheck LIKE \'%sony%\' OR jr_othersoftware LIKE \'%sony%\'";
$res = mysql_query($sql); // This will run the query on the connected datababse
if($row = mysql_fetch_array($res)){ // Since you are using just a SUM to count results, you don't need to loop
echo "Sony Products: ".$row['totalcount']; // $row['totalcount'] is the result of the totalcount from your MySQL query put into the $row variable
}
I hope this helps you out :)
$result = mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
//do something
}

How to check whether SELECT EXISTS returns a value or not?

I am trying to quickly determine if a user_ID is the owner of a 'goal'. I believe my SQL query is good, but I'm trying to find a nice way of checking the result!
In this case, no matter what I put for $obj_id or $user_id, my function returns true. I assume it's because mysql_num_rows is counting even a false result as a row? So what PHP code should I use to check to see if the result exists or not?
Note that I want something short and elegant! I know I could do it the long way (check count(*), return mysql_assoc then check the count value...) but that is long winded and ugly.
Any ideas? Thanks!
$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
if (#mysql_num_rows(mysql_query($query))!=1) {
return false;
} else {
return true;
}
Don't bother with EXISTS. The in-line exists will always give one row containing "true" or "false".
You're looking for either "zero rows" or "at least one row" so change the query to something like this and then check how many rows are returned
SELECT 1 FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id' LIMIT 1
I like gbn's answer the best, but I wanted to point out that this:
if (#mysql_num_rows(mysql_query($query))!=1) {
return false;
} else {
return true;
}
can be simplified to:
return #mysql_num_rows(mysql_query($query)) == 1;
This way is probably faster.
$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
if(mysql_num_rows(mysqli_query($query)) < 1) {
// Nothing found!
}
Counting how many rows match the criteria should be easier:
$sql = SELECT COUNT(*) FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id'
$query = mysql_query($sql);
$result = mysql_fetch_row($query);
return $result[0] >= 1;
SELECT EXISTS always returns a row!
The following code uses the fastest MySql query(according to this answer: https://stackoverflow.com/a/10688065/3710053) and gives in PHP the correct result:
$link = mysqli_connect($DB_SERV, $DB_USER, $DB_PASS, $DB_NAME);
$query = "SELECT EXISTS (SELECT * FROM goals
WHERE goal_ID='$obj_id'
AND user_ID='$user_id'
LIMIT 1)
as `row_exists`";
if(mysqli_fetch_assoc(mysqli_query($link,$query))['row_exists'] ===0) {
// Nothing found!
}
Really working config for MySQL:
$sql="SELECT EXISTS (Select * FROM $dbname.$dbrel WHERE Index_r=$idx AND ... LIMIT
1)";
$r1=mysqli_fetch_row(mysqli_query($conn, $sql));
if (current($r1) == 0) {when no recoeds} else {when exist records }
what about this:
$query = "SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')";
return mysql_query($query) ? false : true;
mysql_result(mysql_query("SELECT EXISTS (SELECT * FROM goals WHERE goal_ID='$obj_id' AND user_ID='$user_id')"),0);

Categories