Check if a certain element is in a table MySQL database - php

I need to check if a certain element is in the table.
Table I am using:
+----------+------------+-------------------+
| ClientId | ClientName | ClientCountryName |
+----------+------------+-------------------+
| 1 | Chris | UK |
| 2 | David | AUS |
| 3 | Robert | US |
| 4 | Mike | ENG |
+----------+------------+-------------------+
This is the code I made, is there a better way?
$c=0;
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if('US'==$row['ClientCountryName']){
$c=$c+1; //If the element is in the table, increment c
}
}
if($c!=0){ //if c is incremented means that the element is one or multiple times in the table
echo 'Element is in the table';
}
else{ //if c is not incremented then the element is not in the table
...
}

You can use count to return count of elements containing US
select count(*)
from users
where ClientCountryName like 'US'
Thanx!

Related

Join tables horizontally and dynamically

I need some help from joining tables horizontally my tables are
+---------+---------+
| Candidates Table |
+---------+---------+
| can_id | Name |
+---------+---------+
| 1 | Liza |
| 2 | Sarah |
| 3 | Jane |
| | |
+---------+---------+
+---------+---------+
| Judges Table |
+---------+---------+
| id | Name |
+---------+---------+
| 1 | judge1 |
| 2 | judge2 |
| 3 | judge3 |
+-------------------+
+---------+---------------+--------+-------+
| Score Table |
+---------+-------+------------------------|
| sco_id | can_id| jud_id |crit_id |score|
+---------+--------+-----------------------+
| 1 | 1 | 2 | 1 | 87 |
| 2 | 1 | 3 | 1 | 89 |
| 3 | 1 | 1 | 1 | 80 |
+------------------------------------------+
I need an output of something like this one..
+---------+---------------+-------------+
| Score board |
+---------+---------+-------------------|
| Name | judge1 | judge2 | judge3 |
+---------+---------+-------------------|
| Liza | 80 | 87 | 89 |
|some data|some data|some data|some data|
|some data|some data|some data|some data|
+---------------------------------------+
notes: crit_id is criteria id from criteria table.
Normally I would use some joins and subqueries but my problems is I need the output dynamically where in if I add a new judges it will automatically generate a new column. I need at least 1 candidate data with all of the judges scores then just loop it with parameters on php to get the other candidates data something like
php loop start
<td>name</td>
<td>judge1 score</td>
<td>judge2 score</td>
php end loop
or if i could get the whole candidates table with judges score much better for me not to loop them per candidate
I've tried to research similar questions like
Concatenate more than two tables horizontally in SQL Server
I've tried to code myself but I got stuck with joining the judges..
SELECT s.sco_id,c.Name,c.Municipalities
FROM `tbl_scoring` s
LEFT JOIN tbl_candidates c ON c.`can_id` = s.`can_id`
WHERE s.can_id = 11
AND crit_id = 1
ORDER BY s.jud_id asc
I need a query that would generate dynamically depending on the number of judges either get candidate data with scores of judge then loop it on php or much way better if i get all the data without looping
Initialize the following arrays:
$judges = [];
$scores = [];
$candidates = [];
Then execute your query, and loop the results. Set those values for each iteration:
$judges[$row['jud_id']] = 1;
$candidates[$row['can_id']] = $row['Name'];
$scores[$row['can_id']][$row['jud_id']] = $row['score'];
Now you want to get the participant judges names, so let's run a SQL query:
$sql = 'SELECT Name FROM judges WHERE id IN (' . implode(',', array_keys($judges)) . ')';
And on every iteration set the judge's name in the $judges array:
$judges[$row['id']] = $row['Name'];
Then for the output:
echo '<tr>';
echo '<td>Name</td>';
ksort($judges);
foreach ($judges as $name) {
echo '<td>Judge: ' . $name . '</td>';
}
echo '</tr>';
foreach ($scores as $candidateId => $data) {
echo '<tr>';
echo "<td>$candidates[$candidateId]</td>";
ksort($data);
foreach ($data as $score) {
echo "<td>$score</td>";
}
echo '</tr>';
}
I used ksort on $judges and $data so the score will fit each judge.
first, we retrieve the judges' ids and name that exist on the score table.
$judges = [];
$query = "SELECT id, name FROM Judges WHERE id IN ( SELECT DISTINCT jud_id FROM Score )";
// execute the query and store the results in the $judges array.
we retrieve the candidates' ids and name that exist on the score table.
$candidates = [];
$query = "SELECT id FROM Candidate WHERE id IN ( SELECT DISTINCT can_id FROM Score )";
// execute the query and store the results in the $candidates array.
then, we join the candidate and score table.
$candidate_score = [];
$query = "SELECT Candidate.name, Candidate.id as candidate_id , Score.jud_id, Score.score FROM Candidate JOIN Score ON Score.can_id = Candidate.id";
// execute the query and store it in the $candidate_score array.
now, for each candidate, we fill its score on the $score_board array.
$score_board = [];
foreach ( $candidates as $candidat )
{
$score_board[$candidat] = [];
foreach ( $judges as $judge )
{
$judge_name = $judge['name'];
$judge_id = $judge['id'];
$score_board[$candidat][$judge_name] = get_judge_score($candidate_score,$candidat,$judge_id);
}
}
this is how the get_judge_score will work:
function get_judge_score ( $scores , $candidate , $judge )
{
$score_filtred = array_filter($scores, function ($score) use ($candidate,$judge) {
return $score['jud_id'] == $judge && $score['candidate_id'] = $candidate;
});
return count($score_filtred) > 0 ? $score_filtred[0]['score'] : 0;
}

need help to get the correct query mysql database php

I am trying to get some JSON data from my database and I can't write the correct SQL query.
I've tried:
$sql = "SELECT arrondissement AS tName, ("SELECT count(*) FROM fcr_table WHERE arrondissement = 'tName';) as tLength FROM fcr_table GROUP BY name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result['tName']->fetch_assoc()) {
echo "name: " .$row['tName']. " " .$row['tLength']. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
To explain more here is an example of what I want to achieve:
+----+-------+-------+
| id | name | score |
+----+-------+-------+
| 0 | test1 | 1000 |
| 1 | test2 | 2000 |
| 2 | test1 | 3000 |
| 3 | test1 | 5000 |
| 4 | test1 | 1000 |
| 5 | test2 | 3000 |
| 6 | test1 | 7000 |
+----+-------+-------+
I want to get JSON data like this:
test1 : count of test1
test2 : count of test2
You can use something like that:
SELECT name AS tName, (SELECT count(*) FROM tests WHERE name=tName) as tLength FROM tests GROUP BY name
if you do not mind aliases... It would allow you to use the current name in subquery and thus get the count. Eventually, Group by will leave only one result instead of many rewrites. If you do PHP query, you will be able to access the data like that $result['tName'] and $result['tLength']

How to do a multiple select from same column as one query

I have a Mysql database table named as_items as below:
-----------------------------------------------------------------------
| itemid | item_type | item_number | item_title | item_content |
-----------------------------------------------------------------------
| 1 | 1 | 2 | First Item | The first item |
| 2 | 2 | 3 | Second Item | The second item |
| 3 | 3 | 5 | Third Item | The third item |
| 4 | 3 | 1 | Forth Item | The forth item |
| 5 | 2 | 4 | Fifth Item | The fifth item |
-----------------------------------------------------------------------
I would like to get multiple queries from the same column which in this case is "item_type" using my php script. In my php script the reference value could one or multiple based on the existence of the character "," in it which my code check for.
if (strpos($itemtypes, ',') !== false) {
$items = explode(',',$itemtypes);
$query = "SELECT ";
foreach ($items as $item){
$query .= "(SELECT * FROM as_items WHERE item_type=$item ORDER BY item_number ASC) AS j$item, ";
}
$result = mysql_query($query) or die(mysql_error());
} else {
$songbook = $songbookids;
$result = mysql_query("SELECT * FROM as_items WHERE item_type= $itemtypes ORDER BY item_number ASC") or die(mysql_error());
}
Take into account the query is based on the php final output. When i use the multiple query I get an error from the server as "Operand should contain 1 column(s) "
NOTE:
Please note the reference item is from my other code where when 2 or 3 item types are selected its output is like "itemtype,itemtype,itemtype" but when only one is selected it is just plain as "itemtype".
Instead of doing the query(s) like that, try this:
$query = "SELECT * FROM as_items WHERE item_type IN ('".str_replace(',', '\',\'', $itemtypes)."') ORDER BY item_number ASC";
$result = mysql_query($query);
This should replace your whole thing, no need to check if , is in the string.

MySQLi join and display details differently from 2 tables

Hello I have actually asked a similar question a while ago but only just realized I did not get an answer that solves my problem.
I have 2 tables in a MySQL DB, that are connected by the same main id, the following code is just a simplified example of the original code:
table1:
+-----------------------+
| main_id | name | type |
+-----------------------+
table2:
+----------------------------------------+
| main_id | secondary_id | color | price |
+----------------------------------------+
the result I want to achieve is to get every row of table 1, and under each one list all the linked by main id rows from table2, for example:
table1 rows:
+-------------------+
| 1 | name1 | type1 |
| 2 | name2 | type2 |
| 3 | name3 | type3 |
+-------------------+
table2 rows:
+----+------+----------+------+
| 1 | 23 | red | 500 |
| 1 | 24 | blue | 600 |
| 1 | 25 | green | 700 |
| 2 | 26 | pink | 400 |
| 2 | 27 | purple | 200 |
| 3 | 28 | white | 100 |
+----+------+----------+------+
result in display:
<h1 class="1">name1, type1</h1>
<div class="23">red,500</div>
<div class="23">red,500</div>
<div class="24">green,700</div>
<h1 class="2">name2, type2</h1>
<div class="25">pink,400</div>
<div class="26">purple,200</div>
And so on...I was using a while loop inside a while loop which wasn't giving me the required result, then I was advised to use MySQL JOIN, but when I do I get all values of the matching ids and cant display the headings only once and then list the related results under it, can someone please help me?
this is a simplified query i was using:
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
//Get details and display
}
}
}
In your description, you use main_id, but in the code you use just id. Not sure which you're really using here - you will have to edit the code below to match your actual column names. If the database column name is actually main_id, then for instance the line with $id = $rows['id'] would have to be $rows['main_id']. Or it won't work.
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
echo '<h1 class="'.$rows['id'].'">'.$rows['name1'].', '.$rows['type'].'</h1>';
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
if ($row2['id'] == $id) {
echo '<div class="'.$row2['secondary_id'].'">'.$row2['color'].', '.$row2['price'].'</div>';
}
}//while
}//else
}//while

Count same values in different column mysql

I need to count how many times in ripeted the same values in different columns for the same id..
I'll try to clarify with an example:
TABLE:
+-----+-----+-----+-----+-----+
| id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
| 1 | A | A | B | B |
+-----+-----+-----+-----+-----+
| 2 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 3 | B | B | A | A |
+-----+-----+-----+-----+-----+
| 4 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 5 | A | A | A | A |
+-----+-----+-----+-----+-----+
| 6 | B | A | A | A |
+-----+-----+-----+-----+-----+
I need to know how many times the value "B" is repeating for any person (ID)..
Is that possible to do that? RESULTS
+-----+-----+-----+
| id | count B |
+=====+=====+=====+
| 1 | 2 |
+-----+-----+-----+
| 2 | 0 |
+-----+-----+-----+
| 3 | 2 |
+-----+-----+-----+
I was thinking to use the function "SUM" but I have no idea how to display just the single ID.
Thanks in advance, hope the question is clear enough!
If there are only four columns:
SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename
No there are 31 columns
That's a problem which you can solve in two ways:
Repeat the condition for the other 27 columns :)
Normalize your structure so that each value is dependent on both the id and a numeric value that represents a calendar.
The PHP way
You can also fetch all columns and let PHP solve this for you:
$res = $db->query('SELECT * FROM tablename');
foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id = $row['id'];
unset($row['id']); // don't count the id column
$count = count(array_keys($row, 'B', true));
printf("ID %d: %d\n", $id, $count);
}
Since you seem to be using mysql_*:
// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';
// In this loop we will construct our SELECT query using the columns returned
// from the above query
while($row=mysql_fetch_array($sql)){
if($row['Field']!='id'){
$new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
}
}
//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like:
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1
$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
echo 'ID - '.$row2['id']."<br>";
echo 'Count - '.$row2['count']."<br>";
}
Note:
mysql_* is deprecated, please consider to migrate to mysqli_*

Categories