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

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.

Related

Check if a certain element is in a table MySQL database

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!

SQL query returns one row too few

SOLUTION: Make sure you don't 'use up' any $responses->fetch_assoc()s before the while loop.
I performed mysqli_fetch_array($responses);.
In php I have this sql query (simplified for your convenience, but the problem remains)
$sql = "SELECT id, content FROM responses ORDER BY RAND()";
$responses = $conn->query($sql);
where the responses table looks like this:
+----+----------+--------+------+
| id | content | userId | part |
+----+----------+--------+------+
| 4 | peewee | 31 | 1 |
| 5 | tallinn | 31 | 1 |
| 6 | dewey | 31 | 1 |
| 7 | stanford | 31 | 1 |
+----+----------+--------+------+
That doesn't format properly so all you need to know is that the id and content rows are different for each entry while the rest is the same for each.
The problem is, when I do a while loop on $responses like so:
while ($row = $responses->fetch_assoc()) {
$responseId = $row["id"];
$content = $row["content"];
echo " id: ".$responseId;
echo " content: ".$content;
}
I always get 1 record fewer than there are. In this case, since there are 4 rows, I would only see 3 echoed. However, it is not always the same 3, nor are they in the same order. If I remove the ORDER BY RAND() clause, then it is always the first record which is left out.
Thanks in advance
Cheers

loops in PHP MYSQL to insert accumulated data from one table to new one

I have a table like this:
id | order_id | code |
1 | 2200 | 489512444756 |
2 | 2200 | 489512444756 |
3 | 2200 | 489512444777 |
4 | 2200 | 489512444777 |
5 | 2200 | 489512444777 |
6 | 2201 | 489512444788 |
7 | 2201 | 489512444788 |
8 | 2201 | 489512444777 |
I'm trying to use for loops to fill another table in MySQL with accumulated data (aggregate the codes to provide qty) with the following columns:
id | order_id | code | qty |
The PHP code used to do this as the following:
mysql_select_db($database, $server);
$query_Recordset1 = "SELECT `order_id` FROM stock GROUP BY order_id ";
$Recordset1 = mysql_query($query_Recordset1, $beharserver) or die(mysql_error());
while ($row_orders = mysql_fetch_assoc($Recordset1)){
foreach ($row_orders as $ord) {
$query_Recordset2 = "SELECT `order_id`, code, COUNT(id) AS qty FROM stock WHERE `order_id` = '".$ord."' GROUP BY code";
$Recordset2 = mysql_query($query, $server) or die(mysql_error());
$row_orders2 = mysql_fetch_assoc($Recordset2);
foreach ($row_orders2 as $itm) {
$insert_qty = "INSERT INTO orders_agg (order_id, code, qty) VALUES ( '".$itm[0]."','".$itm[1]."','".$itm[2]."' )";
$qty = mysql_query($insert_qty, $server) or die(mysql_error());
}
}
}
The code above is not working well, and inserted data in new table are different from what exactly required.
The inserted data looks like this:
id | order_id | code | qty |
1 | 3 | 6 | 0 |
etc...
You should use one SQL statement to do all work. It is:
INSERT INTO orders_agg
(SELECT NULL, `order_id`, code, COUNT(*) AS qty FROM stock
GROUP BY order_id, code)
I'll guess that the problem is that your code is not inserting values into the second table.
You'll need to reference the result values from the array by name -- e.g. $itm['order_id'], $itm['qty'], etc.

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_*

confusion about result structure from joining tables when each row has multiple correspondence on the second table

lets say i have a simple poll aplication
and each user only can choose one option from poll
my poll table
+-----------+---------------------+
| poll_id | question |
+-----------+---------------------+
| 1 | q1? |
+-----------+---------------------+
| 2 | q2? |
+-----------+---------------------+
| 3 | q3? |
+-----------+---------------------+
my options table
+-----------+---------------------+---------+---------+
| option_id | poll_id | option | counter |
+-----------+---------------------+---------+---------+
| 1 | 1 | yes | 254 |
+-----------+---------------------+---------+---------+
| 2 | 1 | no |392333337|
+-----------+---------------------+---------+---------+
| 3 | 2 | yes | 1000 |
+-----------+---------------------+---------+---------+
right now i do something like this to show all the polls i one page
$polls = $db->query("select * from polls ");
foreach ($polls as $poll)
{
echo $poll->question;
$options = $db->query("select * from options where poll_id = '$poll->id' ");
foreach($options as $op )
{
echo '<checkbox />'.$op->option;
}
}
now if i want to do this using joine and one query
$query = "select p.* , o.* from polls p JOIN options o ON p.poll_id = o.poll_id ";
what data structure is going to be used to represent the result ? perhaps a multidimensional array ? i'm not sure how can i printout the result
like in this example result is going to be
resul_array (
poll_id poll_question option option
1 q1 ys no
2 q2 no
}
if i get the result as an array row one would have columns with similar name ? i'm confused
In my opinion, you just need to add "order by" in your query, and store result in an array, and then process the logic on it.
Something like:
$polls = $db->query("select p.* , o.* from polls p JOIN options o ON p.poll_id = o.poll_id order by p.poll_id");
$currentPoll = $polls[0];
foreach ($polls as $poll)
{
if($poll->poll_id != $currentPoll->poll_id) {
echo $poll->question;
$currentPoll = $poll;
}
echo '<checkbox />'.$poll->option;
}
HTH.

Categories