Searching for multiple numbers in multiple number field - mysql

-----ID
1
5
1,6
3
4
1,36
1
I have these '1,6,36' number to search.
It should find any row that contains 1 OR 6 OR 36 (e.g. total 4 rows in the above table)
I tried
FIND_IN_SET(ID, '1,6,36')
ID IN (1,6,36)
None of them worked.
Any idea how to achieve this ?

FIND_IN_SET(1, ID) OR
FIND_IN_SET(6, ID) OR
FIND_IN_SET(36, ID)

You have to do a sql query called IN, and you should do it as follows:
$id_array = array(1, 6, 36)
$sql = "SELECT * FROM table WHERE id IN ($id_array)";
$search = mysqli_query($sql_connection, $sql);
Then to display, you have to do a PHP loop like follows:
while($ids = mysqli_fetch_array($search)) {
echo '<h3>'.$ids['field_from_db'].'</h3><br />';
}

Related

How to check if a variable equals to part of one of the columns in a table in the Database?

For example I have a variable $num = 123; and another one called `$name=joe;' , and there is a Database that contains a table called "data" and inside this table there are two columns (num [type=varchar(255)] - name[type=varchar(255)]) .
For example these query exists in the DB :
num = 123456 , name = joe
How to make a check that the first "3" numbers equals the $num variable and the name equals variable $name ?
I tried this but it didn't work:
SELECT * FROM data Where SUBSTRING(num , 0 , 3) = '123' AND name = 'joe'
In MySQL, substring indexing starts at 1:
WHERE SUBSTRING(num , 1 , 3) = '123' AND name = 'joe'
But LEFT() or LIKE would more commonly be used:
WHERE LEFT(num , 3) = '123' AND name = 'joe'
WHERE num = '123%' AND name = 'joe'
The advantage of LIKE is that it can make use of an index . . . even one on (name, num).
The MySQL substring() function is 1-based, not 0-based, so this should work for you:
SELECT * FROM data Where SUBSTRING(num , 1 , 3) = '123' AND name = 'joe'

Not an Intersect (IN) but sort of. Where Col a row x intersects with col b.Mysql

I have a matrix table. 6 columns wide and 6 rows deep.The first column has the numbers 0, 5,4,3,2,1 in that order. The first row in the table is 0,1,2,3,4,5
so like this:
Column names RM0 RM1 RM2 RM3 RM4 RM5
0 1 2 3 4 5
5
4
3
2
1
each of the rows has words in it ie, MEDIUM, HIGH, CRITICAL etc.
I have a form the user fills out that requires them to give a rating from 1-5 in two categories. Their selections correspond to one of the words in the matrix. SO..after all that...I need to be able to select from the table something like this:
SELECT FROM TBLX WHERE RM0=4 INTERSECTS WITH RM4
I have look at IN but everything I see so far still requires you to have another WHERE x=y part. Could I dump the whole table into an array somehow get what Im after? As you can see, Im clueless in this regard.
You can do something like this:
SELECT CASE :b2
WHEN 1 THEN t.rm1
WHEN 2 THEN t.rm2
WHEN 3 THEN t.rm3
WHEN 4 THEN t.rm4
WHEN 5 THEN t.rm5
ELSE ''
END AS `the_word`
FROM TBLX t
WHERE t.rm0 = :b1
I'm confused by the table design. And even more confused by the first row... if you want to get that incorporated in the query, that would be inordinately complex.
In terms of a normal relational design, we'd represent this as rows for each pair of values, with a single word on each row.
mymatrix
x_rating y_rating the_word
-------- -------- --------
1 1 LOW
1 2 LOW
1 3 MEDIUM
1 4 MEDIUM
1 5 MEDIUM
2 1 LOW
2 2 MEDIUM
2 3 MEDIUM
...
5 5 HIGH
An example of a query to get "the word" would be something like this:
SELECT mx.the_word
FROM mymatrix mx
WHERE mx.x_rating = :b1
AND mx.y_rating = :b2
To use that same query pattern with the original table, we could get that original table converted to look like the mymatrix table, using the values from the RM1 through RM5 columns in the RM0=0 row as the y_rating value. The SQL to do that is rather cumbersome:
SELECT mx.the_word
FROM (
SELECT t1.rm0 AS x_rating
, s1.rm1 AS y_rating
, t1.rm1 AS the_word
FROM mytable t1
JOIN mytable s1
ON s1.rm0 = 0
AND t1.rm0 > 0
UNION ALL
SELECT t2.rm0 AS x_rating
, s2.rm1 AS y_rating
, t2.rm1 AS the_word
FROM mytable t2
JOIN mytable s2
ON s2.rm0 = 0
AND t2.rm0 > 0
UNION ALL
SELECT t3.rm0 AS x_rating
, s3.rm1 AS y_rating
, t3.rm1 AS the_word
FROM mytable t3
JOIN mytable s3
ON s3.rm0 = 0
AND t3.rm0 > 0
UNION ALL
SELECT t4.rm0 AS x_rating
, s4.rm1 AS y_rating
, t4.rm1 AS the_word
FROM mytable t4
JOIN mytable s4
ON s4.rm0 = 0
AND t4.rm0 > 0
UNION ALL
SELECT t5.rm0 AS x_rating
, s5.rm1 AS y_rating
, t5.rm1 AS the_word
FROM mytable t5
JOIN mytable s5
ON s5.rm0 = 0
AND t5.rm0 > 0
) mx
WHERE mx.x_rating = :b1
AND mx.y_rating = :b2
I ended up taking a different route. I still used the matrix table but instead of trying to access when I need to retrieve information I queried the table once, took all the information and put it into an array like this:
sql = "SELECT * FROM `tblriskmatrix`";
if (!$conn->query($sql)) {
echo "query failed: (" . $conn->errno . ") " . $conn->error;
}
$result = $conn->query($sql);
$arrayOfMatrix = array();
while ($row = $result->fetch_assoc()) {
$arrayOfMatrix[] = $row;
}
I then put the array into a session variable like this:
$_SESSION['arrayOfMatrix'] = $arrayOfMatrix;
I then created some functions to get the keys pressed and passed them to another function that did an ajax call, passing the variables of the key presses script that took those variables and passed them into my session variable and returned the desired result. Like this:
session_start();
$a = $_GET['var_a'];
$b = $_GET['var_b'];
$response = array('response' => $_SESSION['arrayOfMatrix'][$a]["RM$b"]);
echo json_encode($response);
The response is then passed to a form element and displayed. So with the matrix table in the session variable as an array I can easily extract the contents of what is in cell of row x within column y. Not sure if its the most technically correct route but it works.

SQL selecting rows from two seperate tables with one being selected at random

I am currently developing a multiple choice football quiz driven by a back end database. For my database I have created 2 tables.
The first table is called questions and contains the following data
Id, Team1, Team2, Score1, Score2, Year and Round as the attributes
The second table I have is for answers and contains the following data
Id and Team
Sample Data is shown below
Questions:
1,Spain,Holland,0,0,2010,Final
2,England,Germany,1,4,2010,Last 16
Answers
1,England
1,France
1,Germany
1,Brazil
1,Spain
1,Holland
I have kept the Id of all teams as 1 so that they can all be in the same answer set when called
The purpose of my application is to ask a question to the user using a template as shown below
$thisQuestion = 'Which team defeated '. $team1.' '.$score1.' - '.$score2.' in the '. $round .' of the '.$year.' world cup';
Below the question I wish to have 4 teams shown to the user as possible answers with 3 being drawn randomly from the answers table and the 4th being the correct answer.
So far I have only been able to call 3 random teams from the answer table using the following code
$sql2 = mysql_query("SELECT * FROM answers2 WHERE id=1 ORDER BY RAND() LIMIT 3");
Any help would be appreciated
The full sample code for the page is shown below
<?php
session_start();
require_once("scripts/connect_db.php");
$countArray = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$outputText = "";
$answerText = "";
$r = "";
$sql = mysql_query("SELECT id FROM questions");
$numberOfQuestions = mysql_num_rows($sql);
if(!isset($_SESSION['a_array']) || $_SESSION['a_array'] < 1){
$currQuestion = "1";
}else{
$countArray = count($_SESSION['a_array']);
}
if($countArray > $numberOfQuestions){
unset($_SESSION['a_array']);
header("location: menu.php");
exit();
}
if($countArray >= $numberOfQuestions){
echo '<p>There are no more questions. Please enter your name and click next to find out your score</p>
<form action="userResults.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="submit" value="Finish">
</form>';
$outputText = ''.$r.','.$answerText.', ';
echo $outputText;
exit();
}
$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysql_fetch_array($singleSQL)){
$id = $row['ID'];
$team1 = $row['Team1'];
$team2 = $row['Team2'];
$score1 = $row['Score1'];
$score2 = $row['Score2'];
$round = $row['Round'];
$year= $row['Year'];
$thisQuestion = 'Which team defeated '. $team1.' '.$score1.' - '.$score2.' in the '. $round .' of the '.$year.' world cup';
$question_id = $row['ID'];
$r = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers2 WHERE id=1 ORDER BY RAND() LIMIT 3");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['team'];
$correctAnswer = $team2;
$answerText .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correctAnswer.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$outputText = ''.$r.','.$answerText.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span><br />';
echo $outputText;
}
}
?>
This is not a complete answer but I think you can easily expand it to do what you want. The main problem (as I understand it) is this: you need a list of four team names randomly selected except it must include one specific team name and with all 4 arranged randomly.
It turns out to be fairly simple in MySQL. Here is a simple table containing just the team names for illustration.
CREATE TABLE Teams (
Team VARCHAR( 20 )
);
insert into Teams( Team )
SELECT 'Spain' UNION ALL
SELECT 'Holland' UNION ALL
SELECT 'England' UNION ALL
SELECT 'Germany' UNION ALL
SELECT 'Brazil' UNION ALL
SELECT 'Mexico' UNION ALL
SELECT 'Uraguay' UNION ALL
SELECT 'Sweden' UNION ALL
SELECT 'France';
Then get Team1 from your question. Here I've just set it to a value.
set #Team1 := 'Germany';
select Team
from(
SELECT Team
FROM Teams
WHERE Team <> #Team1
ORDER BY Rand()
limit 3
) T
union all
SELECT #Team1
order by Rand();
This produces four different names each time you execute it, except that the list will always include Germany. You might consider changing the last line to order by Team as a random list of names will still be random if arranged in alphabetical order.

MySQL order by IN array

I have a MySQL script like this: SELECT id, name FROM users WHERE id IN (6,4,34)
The sequence in the IN(...) array is very important. Is it possible to get them in the given sequence?
You can use the MySQL FIELD function to keep it compact;
SELECT id, name
FROM users
WHERE id IN (6, 4, 34)
ORDER BY FIELD(id, 6, 4, 34);
Try
SELECT id, name FROM users WHERE id IN (6,4,34) order by FIELD(id,6,4,34)
You can use any expression in the ORDER BY clause, including a 'CASE':
ORDER BY CASE id
WHEN 6 THEN 1
WHEN 4 THEN 2
WHEN 34 THEN 3
END ASC
If your list comes from the application programming layer, you might build this with the following (PHP here):
$sortVal = 1;
foreach($ids as $id_val) {
$cases[] = sprintf('WHEN %i THEN %i', $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE id ' . implode($cases) . ' END ASC';
However, I'll mention that Joachim's answer is quite elegant :-)
A complete example based on Chris Trahey answer.
$ids = array("table1", "table2", "table3");
$sortVal = 1;
foreach ($ids as $id_val) {
$cases[] = sprintf("WHEN '%s' THEN %u ", $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE `tableName` ' . implode($cases) . ' END ASC';
$result = mysqli_query( $con, "
SELECT DISTINCT tableName
FROM `table`
$order_by");

Select based on Multiple Rows

All,
Say I have the following data set:
id docId meta_key meta_value
1 356 rating 2.0
2 356 total_votes 10
3 356 total_rating 200
Basically I'm trying to pull all the values in my meta_value column by selecting the docId of 356 and only selecting the meta_key rows that I have listed.
Any ideas how to do this in a single query?
EDIT: My desired output would be something like this:
rating total_votes total_rating
2.0 10 200
I'm trying to get it so that I can use these values with a mysql_fetch_array in PHP.
Thanks!
What you are asking for is a pivot table. Unfortunately, MySQL doesn't provide functions for generating pivot tables.
It's still doable, but with more than two columns, it starts to get messy.
I would loop through the records in PHP and build the array.
To borrow slightly from Ghost Developer's answer:
$assoc_array = array();
$query = "SELECT meta_key, meta_value FROM table WHERE docId=356";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)) {
$assoc_array[$row['meta_key']] = $row['meta_value'];
}
mysqli_free_result($result);
All columns from all rows for docId 356
SELECT * FROM mytable WHERE docId = 356;
Only the meta_value column from all rows for docId 356
SELECT meta_value FROM mytable WHERE docId = 356;
Get all values as a comma-separated list for docId 356
SELECT GROUP_CONCAT(meta_value) meta_values FROM mytable WHERE docId = 356;
$query = mysql_query("SELECT * FROM table WHERE docId=356");
while ($result = mysql_fetch_array($query)) {
$metaKey = $result['meta_key'];
$meta_value = $result['meta_value'];
echo $meta_key.' : '.$meta_value.'<br>';
}