I have a table with entries such as:
123 (DVD)
123 [DVD] [2007]
125 [2009]
189 (CD)
when I present these to the user in an autocomplete field I do away with anything between either () or [] as these are not relevant, but, as you can see from the list above, that leaves me with two entries for 123 which appear in the dropdown... is there anyway to further suppress duplicates? Sometimes there can be as many as 5 or 6 which looks wrong to say the least! Code below:
// db select
$query = "SELECT $title FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id') AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8";
$result = mysql_query($query);
$output_items = array();
// while loop to print results
while($row = mysql_fetch_array($result)) { $output_items[] = $row[$title]; }
$output_items = preg_replace('/\[.*?\]|\s*/', '', $output_items); // remove [blah]
$output_items = preg_replace('/\(.*?\)|\s*/', '', $output_items); // remove (blah)
print(implode("\n", $output_items));
Many thanks
The array_unique() function removes duplicate values from an array, in your case the $output_items array.
Take a look at http://php.net/manual/en/function.array-unique.php
You can use array_unique ( array $array ) to remove all duplicates before imploding.
Related
In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';
I have the following codes:
$spaces=0;
$str="bike car ";
for($i = 0; $i < strlen($str); $i++)
{
if($str[$i]==" ")
{
$spaces+=1;
}
}
$names=explode(" ",$str);
The above code is used to split the words inside the string. How do i do a db query wherein i get the id of the names(words in the string i separated).
Assuming, i have a price table
The table has lets say 2 cols, item name and id
How do i parse DB query wherein i need to get the ids of the item names listed.
I guess you want to get the id of exploded $name simply you can use $this->db->where_in()
example :
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
See the documenation here : Where In Query
So the next line of your code maybe seems like this one :
$names = explode(" ",$str);
$this->db->select('id')
->where_in('your_table_name',$names);
$query = $this->db->get();
$result = $query->result_array();
then you can use the $result by
foreach($result as $r){
echo 'The id is :'.$r['id'];
}
You can simple use array_keys and array_values to traverse you array keys and values
//sample array
Array
(
[1334] => Face Towel
[4552] => White Socks
[3442] => Lotion
[6643] => Pants
[4432] => foobar
[5532] => bar
)
$items = implode(',',array_values($array)); //will get the array values
$itemid = implode(',',array_map('intval',array_keys($array))); //will get the array keys
$this->db->where_in('items', $items);
// where items IN ('Face Towel','White Socks','Lotion','pants','foobar','bar')
$this->db->where_in('itemid', $itemid);
// where itemid IN (1334,4552,3442,6643,4432,5532)
Note that i used array_map to loop through each keys and cast every key as integer.
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);
I'm here today because i'm under a minor issue that i can't seem to solve and it's why it brings be here.
The issue is that i'm trying to get multiple ID's from a $_GET variable to print out. I tried to use array and great, it works but the thing is it makes separate arrays with [0] and i need it to be as one in the same array not array() array() which is what its doing.
So i'm using while() with mysql_fetch_array to get the results off the database and it depends on the $_GET from the url in-order to grab the correct id's. So in the URL i pass in api.php?do=remove&id=1,4,7 it will only print out the first id and not the others as a name. As i said i tried with array() and this is what came out :
Array
(
[0] => BzlXO.jpg
)
Array
(
[0] => cHZTk.jpg
)
Array
(
[0] => 9yset.jpg
)
Array
(
[0] => Ss04V.jpg
)
i don't understand why its doing that as i need it to be in one array as in
Array (
[0] => BzlXO.jpg,
[1] => cHZTk.jpg,
[2] => 9yset.jpg,
[3] => Ss04V.jpg
)
So that way when i implode them it will show as text as in:
"You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
with something like
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
Here is my code:
This is the URL "api.php?do=remove&id=1,4,7"
$ID = $_GET['id'];
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
$api_message = "You removed image(s) $name";
}
}
The OUTPUT :
You removed image(s) BzlXO.jpg
but i need it to be:
The OUTPUT :
You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
Any help with this will be much appreciated, if any more information is needed please let me know and i'll include
Thanks
In addition to the solution posted by raina77ow, there is also a problem with the control flow in that you are executing the DELETE FROM uploads WHERE ID IN (...) statement for each iteration of the while loop. This will delete all the records on the first iteration. You need to change it to something like:
$ID = $_GET['id'];
$names = array();
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID = {$iName['ID']} AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$names[] = $iName['imagename']);
}
}
$name = implode(",", $names);
$api_message = "You removed image(s) $name";
Perhaps you need to fill an array declared before the loop instead, like that:
$images = array();
while( $iName = mysql_fetch_array($result)) {
...
$images[] = $iName['imagename']; # pushing the deleted image into that array
}
...
$names = implode(', ', $images);
And I strongly suggest at least checking the possibility of using mysqli set of functions instead (or PDO, that's even better in my opinion, but might be a step too huge for your codebase). )
You should revise your code as to protect it against invalid values and reduce the possibility of failures.
As to your specific problem, there's no need to place values from one array inside another one, just to the goal of imploding it to a string. You can simply use string concatenation to keep adding the desired values.
This suggestion fixes you issue: code comments are to explain whats happening
// initialize the user message with the success string
$api_message = "You removed image(s): ";
// check if the URL variable exists and contains values
if (isset($_GET['id']) && $_GET['id']!='') {
// clean the values a litle bit to prevent code injection
$ID = strip_tags(trim($_GET['id']));
// prepare the query (more compatible string concatenation)
$query = "SELECT ID, imagename FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
// query the databse
$result = mysql_query($query);
// check for results
if (is_resource($result) && mysql_num_rows($result)>=1) {
// get total records
$counter = mysql_num_rows($result);
// run by each result found
while($iName = mysql_fetch_array($result)) {
// delete all from the database
$querys = "DELETE FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
$results = mysql_query($querys);
// check if the returned result is false
if (!$results) {
// replace the user message with a fail information
$api_message = 'Failed to get a Removal result';
} else {
// decrease the counter
$counter--;
// update the user message and add a "," if this is not the last name
$api_message.= $iName['imagename'] . (($counter==0)?(''):(', '));
}
}
} else {
$api_message = 'ups... failed to talk with the database';
}
} else {
$api_message = 'ups... no ids collected';
}
Related reading:
PHP strip_tags
strip_tags — Strip HTML and PHP tags from a string
PHP trim
trim — Strip whitespace (or other characters) from the beginning and end of a string
PHP is_resource
is_resource — Finds whether a variable is a resource
I need to sort an associative-array in the exact order of the content of another array.
The Arrays are retrieve by 2 separate sql-requests (stated below). The requests could not be combined to only one request, so I have to sort the second array into the order of the first one.
These are the arrays:
#Array which contains the id's in needed order
$sorting_array = array(1,2,3,8,5,6,7,9,11,10...);
#Array which contains the values for the id's, but in order of "id" ASC
$array_to_sort = array(
array("id" => "1", "name" => "text1", "help" => "helptxt2");
array("id" => "2", "name" => "text2", "help" => "helptxt2");
);
The SQL-Queries:
SQL-Ouery for $sorting_array: (the db-field 'conf' is setup as "text", maybe this is my problem so that I have to first explode and implode the entries before I could use it for the next query.)
$result = sql_query("select conf from config where user='me'", $dbi);
$conf = sql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
$new = array($temp[0], $temp[1], $temp[2], $temp[3],$temp[4],
$temp[5], $temp[6], $temp[7], $temp[8], $temp[9],
$temp[10], ...);#Array has max 30 entries, so I count them down here
$sorting_array = implode(',', $new);
SQL-Ouery for $array_to_sort:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
I could access $array_to_sort as follows to see the content one by one:
(if the lines below don't match the array above, than I mixed it up. However, the lines below is what brings the content)
echo $array_to_sort[0]["id"];
echo $array_to_sort[0]["name"];
echo $array_to_sort[0]["helptxt"];
But it is sorted by "id" ASC, but I need exactly the sorting as in $sorting_array.
I tried some things with:
while(list(,$array_to_sort) = each($sorting_array)){
$i++;
echo $array_to_sort . "<br>";
}
which only brings the Id's in the correct order, but not the content. Now I'm a bit confused, as I tried so many things, but all ended up in giving me the same results.
Maybe the sql-query could be done in one step, but I didn't brought it to work.
All results to my searches just showed how to sort ASC or DESC, but not what I want.
Furthermore I must confess that I'm relative new to PHP and MySQL.
Hopefully some one of you all could bring me back on track.
Many thanks in advance.
To fetch your results:
$result = mysql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
$array_to_sort = array();
while ( ($row = mysql_fetch_assoc($result)) !== false ) {
// associate the row array with its id
$array_to_sort[ $row[ "id" ] ] = $row;
}
To display them in order of $sorting_array:
foreach ( $sorting_array as $id ) {
// replace the print_r with your display code here
print_r( $array_to_sort[ $id ] );
}
And a bonus tip for the code fetching $sorting_array:
$result = mysql_query("select conf from config where user='me'", $dbi);
$conf = mysql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
// limit to 30 ids
$new = array();
// no need to do this manually, use a loop
for ( $i = 0; $i < 30; ++$i )
$new[] = $temp[ 0 ];
$sorting_array = implode(',', $new);
Its a little hard to tell because there is a lot going on here, in the future you'll probably get better/more responses if you ask several simple questions and figure out yourself how to make the answers fit together.
Your best bet long term is going to be to restructure your SQL tablessuch that you can combine these query together. You can do what you're asking in PHP, but it's going to be slower than doing it in MySQL and much more complicated.
To do what you're asking (pretty slow in PHP):
$sorted = array();
foreach ( $sorting_array as $id )
{
foreach ( $array_to_sort as $values )
{
if ( $values['id'] == $id )
{
$sorted[] = $values;
break;
}
}
}
what I tend to do in such a situation is first to rearrange the array with the data. so the keys represent ids
In your case:
$array_to_sort_ids = array();
foreach ($array_to_sor as $item)
{
$array_to_sort_ids[$item['id']] = $item;
}
Then sorting is as simple as:
$array_sorted = array();
foreach ($sorting_array as $id)
{
$array_sorted[] = $array_to_sort_ids[$id];
}
This solution is quite efficient, since you only have 2 foreach loops.
EDIT!!!
As I couldn't edit my question anymore, I just like to state my solution this way:
The tip to rethink my database was what brought me to some testings and then I found the solution, with the following query:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'
ORDER BY FIELD(id,$sorting_array)");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
Just the line:
ORDER BY FIELD(id,$sorting_array)
will do the trick. It orders the results the way you want, even if this means 1,4,2,3,9,7,...
Sometimes it's so easy, when you know where to look.
Thanks again!!!