Mysql search with semi colon delimited string - php

I have 2 tables that look like this
table A table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......
What i plan to do is something like this, where i query one table. loop thru the array of results and explode the data with the semicolon delimiter. then loop thru that new array and query it to get the data (note code below not tested)
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
while ($row = mysql_fetch_array($query)) {
$arr = explode(';', $row['features']);
for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}
print_r($r);
is there a way i can achieve this just in mysql, where i match the column in tableB with the ID's in tableA? or maybe by not using a nested loop? performance is key. coz both tables have more than 25k rows of data.
thanks in advance

Check out this code. Reduced few loops.
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);
$str = implode(",", $arr);
$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}

What you are looking for is the IN function
This will take an array of id's and give you every result in a single query.
So your code should look like this after you apply it
while ($row = mysql_fetch_array($query)) {
$new_query = str_replace(";", ",", $row['features']);
$sql2 = "SELECT * FROM `tableA` WHERE `id` IN ($new_query)";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}

Related

Error: Array to string conversion error

Firstly I am randomly selecting the ID from my table. That part works fine but the next part doesn't. The next part is selecting the ID's row, e.g. if the ID is 6, then it should select all the fields related to 6.
my table is like this:
------------------------------
|ID|Name|Email |Password|
------------------------------
|1 |Amy |H#gmail.com|jaaaaaaa|
------------------------------
|2 |Bob |1#gmail.com|haaukanm|
------------------------------
|3 |Bill|aa#mail.com|fsoji443|
------------------------------
This is my code:
<?php
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
?>
The issue is here:
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
here $data2 is not a single value, its an array and you are trying to compare it in WHERE like a string, that's why the error. Instead try $data2['id'] like:
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
or
$c = "SELECT * FROM `tblaccounts` WHERE ID=".$data2['ID']; // Sinlge quote is not required if `ID` is `int`
Because your $data2 is an array, this is should work
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
You are getting this error as you are comparing array in where clasue.
Your $data is an array like below
$data = array(
'ID'=>2
'Name'=>'Bob',
'Email'=>'1#gmail.com',
'Password'=>'haaukanm'
);// say record with id 2 is fecthed
So use $data['ID'] in your where clause

how to explode mysql table data in php

In mysql table table data, one column has multiple value like this,
code name
1,2,3 a
4 b
My desired output will be
code name
1 a
2 a
3 a
4 b
Here is my code:
$sql="SELECT * FROM hsc_sub group by sub_name order by sub_code";
$res = app_db_query($app,$sql);
while($row = mysqli_fetch_assoc($res)){
//enter code here
$subj[] = $row;
$subj[] = explode(",",$row['sub_code']);
}
Within the ForEach Loop, we can achieve your requirement.
$subCode[];
$name[];
echo("Code");
echo("\t");
echo("Name");
echo("\n");
$sql="SELECT * FROM hsc_sub group by sub_name order by sub_code";
$res = app_db_query($app,$sql);
while($row = mysqli_fetch_assoc($res)){
$nm = $row['sub_name']
$sub[] = explode(",",$row['sub_code']);
foreach($sub as $item)
{
$name.push($nm);
$subCode.push($item);
echo($item);
echo("\t");
echo($nm);
echo("\n");
}
}

While loop not returning correct output when nested

I have a while loop that is supposed to first get the individual_id from a table called submittedresume using the job_id that it gets from another function. It would then use that id in another while loop to get the first_name and last_name from the individual table. It would then use another while loop to get the submitted_id from the submitted resume table.
I split the first and last while loop to get distinct values from the output.
My first while loop. It first gets the individual_id from a table called submittedresume using the job_id that it gets from another function. It gives me the correct output of two user ids: 9 and 4.
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
}
This is the second inner while loop. It gives me an output of Mary Jane (No repeat) and Tom Sawyer.
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
echo $first;
echo $last;
}
This is my whole function:
public function displayApplications($id){
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
$sqlquery = "SELECT DISTINCT resume_title FROM submittedresume WHERE individual_id='$indvId' order by submitted_id";
$data = $database->query($sqlquery);
if (mysqli_num_rows($data) == 0) {
echo "Database is empty <br>";
} else {
while (($name = mysqli_fetch_array($data))) {
echo $first . " " . $last . " "."<a href=handleDownload.php?id=$id>$name[0]</a><br>";
}
}
}
}
}
This is what I'm getting right now:
first_name | last_name | resume_name
Mary | Jane | resume_1
Mary | Jane | resume_2
This is what I'm looking for:
first_name | last_name | resume_name
Mary | Jane | resume_2
Tom | Sawyer | resume_1
I think after while use foreach loop:
For example:
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
$details = mysqli_fetch_array($result);
foreach($details as $key => $value){
echo 'Key: '. $key . ' '. 'Value: '. $value;
}
$indvId = $row[0]; is returning the 1st item in the result array
I personally would use a foreach loop but you could do it the way you have it by adding a counter ie: $count = 0; before the loop and $count++; inside the loop and $indvId = $row[$i];

Add to array in comma separated values from database

my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories