Separate ids by commas and quotes - php

I got an array of ids that I want to use inside an IN statement (sql). However this can only be done when it is written correctly, for example: IN ('12', '13', '14')
How can I change an array of ids into that format? This means adding quotes around every number, and after every number surrounded by quotes a comma, except for the last one in the array.
My code:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
I later want to use it like this:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";

Do this as a single query! SQL engines have all sorts of optimizations for working with tables, and doing the looping in your code is usually way more expensive.
The obvious query for your purposes would be:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;

Use implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''

Have you tried to implode()?
Use ", " as glue. You will have to edit the string yourself to add a " at the beginning and end.
More info: http://php.net/manual/en/function.implode.php

Alternatively you can use single join query, like this.
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1

If the column's type in the DB is integer you do not actually need to quote the values, but in case it isn't, you can use array_map to quote every item in the array, then implode to join them with commas:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
Result:
SELECT * from mytable where id in ('1','2','3','4','5')

You can do something like this:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
This will give you :
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1

Related

PHP/MySQL - How to select id from table and echo in array

How to make the array of id that we call from a table?
What I want is like this :
$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.
Thank you
Code :
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){
$a = implode(',',(array)$row['id_add_user']);
echo $a;
}
What I get from echo $a is 12345 not 1,2,3,4,5
Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.
$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id_add_user']);
}
echo implode(", ", $result);
Collect necessary values into an array.
$a = [];
while(...){
$a[] = $row['id_add_user'];
}
echo implode(',', $a);
You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL
You can further simplify it to...
$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));
mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.
$array = array(1,2,3,4,5);
Use below SQL query for selecting the array id data
SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;

Pass an array as parameters to SQL procedure

I have SQL procedure in which I'm using an IN statment. It goes like this:
SELECT * FROM costumers WHERE id IN('1','2','12','14')
What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?
You can implode on this case:
$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')
or if you do not want any quotes:
$ids = implode(",", $array);
You can use PHP function Implode
$array = array("1","2","12","14");
$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"
implode() is the right function, but you also must pay attention to the type of the data.
If the field is numeric, it is simple:
$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));
But if it's a string, you must play with single and double quotes:
$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));
This should do the trick
$array = array('1','2','12','14');
SELECT * FROM `costumers` WHERE `id` IN('{$array}');
Try imploding the php into an array, and then interpolating that string into the SQL statement:
$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);
SELECT * FROM customers WHERE id in ($string);
use PHP's join function to join the values of an array.
$arr = array(1,2,12,14);
$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";

Output mysql result as an array of the form (column name => possible values for column name)

I have database such as
I want to create an associative array such that each att_name value is associated with its possible values from att_value:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
What is the best way to achieve this?
While it is easily possible to do this simply by selecting the results you want and iterating them in PHP to create the data structure you want, you could sub some of the work out to MySQL with GROUP_CONCAT():
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
Of course, this only works if your values will never contain the character (or sequence of characters) you use for the SEPARATOR in the MySQL query, so the safer pure-PHP way would be:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
Try below:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value by a <!>. I use this <!> so it highly impossible to have a value inside att_value with this. If you think you would someday use this, take another separator. Example : [{--}], _SEPARATOR_, [_-CUT-_], etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

PHP & MySQL: Count and order most popular values in an array and then print

I am wanting to order my array by how many times a value comes up in that array and also then print only the highest 6 results.
This is what I have at the moment:
$delimiter = " ";
$tags = array();
$sql = mysql_query("SELECT tags FROM share WHERE site_id = $id");
while($result = mysql_fetch_assoc($sql)) {
$tags_new = explode($delimiter, $result['tags']);
$tags = array_merge($tags , $tags_new);
}
Hum... You can do that:
while($result = mysql_fetch_assoc($sql)) {
$tags_new = explode($delimiter, $result['tags']);
foreach($tags_new as $tag){
$tags[$tag]++;
}
}
After, you need to sort by value, using function sort or rsort (desc).
rsort($tags);
Last, you need slice and get only 6 first:
$high_tags = array_slice($tags, 0, 6, true);
Edit: showing key and value:
foreach($high_tags as $key => $value){
echo "{$key}: {$value}";
}
Or just do:
$high_keys = array_keys($high_tags);
var_dump($high_keys);
Bye :)
You can do this in MySQL with the following query:
SELECT tags, COUNT(tags) AS tag_count
FROM share WHERE site_id = $id
GROUP BY tags
ORDER BY tag_count DESC
LIMIT 6;
This will select the top 6 tags with the highest count. You can then loop over them similar to the PHP code you already have.

Categories