Add to array in comma separated values from database - php

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 />';
}

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

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

How can I store this data in arrays

I have 3 tables users alerts and articles a user can setup an alert so when a new article is added that match his profile he will get an email
I am trying to write a small code to do this task
and this is what I came up with so far
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
while ($users = mysqli_fetch_row($result_users)) {
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts)) {
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
}
}
Now what I want to do is to store the result this way
Put each alert category + keyword + count in an array then put it in an array that contain the user id and email
So at the bottom I can loop through the users and send to the user with id 1 and email example#website.com
a table like this
Category | Keyword | articles count
Health | Diet | 5
Buisness | Banks | 2
I hope you understood my idea, I am very confused and dizzy I didn't even know what to type in the search box
Take one array outside of while and add 3 variable in array when loop is executed.
i added 2 lines in your code which are.
$response = array();
and
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
Complete example
<?php
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
$response = array();
while ($users = mysqli_fetch_row($result_users))
{
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts))
{
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
}
}
echo "<pre>";
print_r($response);

Mysql search with semi colon delimited string

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'];
}
}

Group By 2 Columns with similar info to link with a 2nd table

I have two columns with similar info:
column 1 = item 1, item 3, item 5
column 3 = item 3, item 5, item 8
I want to display how many of each item are in total from both columns.
I have this:
$sql = mysql_query("SELECT FirstTypeID, SecondTypeID, ThirdTypeID, DesignID, COUNT(DesignID) FROM designs WHERE Approved = '1' GROUP BY FirstTypeID, SecondTypeID, ThirdTypeID");
while ($row = mysql_fetch_array($sql)) {
$DesignID = stripslashes($row['DesignID']);
$FirstTypeID = stripslashes($row['FirstTypeID']);
$SecondTypeID = stripslashes($row['SecondTypeID']);
$ThirdTypeID = stripslashes($row['ThirdTypeID']);
$Total = stripslashes($row['COUNT(DesignID)']);
}
$result2 = mysql_query("SELECT * FROM types WHERE TypeID = '$FirstTypeID' OR TypeID = '$SecondTypeID' OR TypeID = '$ThirdTypeID'");
while ($row2 = mysql_fetch_array($result2)) {
echo "<li><a href='index_type.php?TypeID=".$row2{'TypeID'}."'>".$row2{'TypeName'}." (" . $Total . ")</a></li>";
}
but I'm not getting the result that I want, it's only giving me results from one column.
I'm not sure if this is what you are asking for but well here it is
$typesIDs = array(type0 => "", type1 => "", type2 => ""...);
foreach($typesID as $index=>$value){
$query = "SELECT COUNT(*) AS total FROM designs COLUMN1 = ".$index." OR COLUMN2 = ".$index;
$sql = mysql_query($query);
$row = mysql_fetch_array($sql);
array[$index] => $row["total"]
}

Categories