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;
Related
I tried this:
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
var_dump($values);
echo $values;
?>
But I got this on my webpage:
C:\wamp64\www\site\site.php:18:
array (size=2)
0 => int 1
'' => int 1
Am I missing something?
$values is an array, so you need to access the direct value if you want to echo it. The max ID is 1, as shown by your var_dump() - but you get two results from the array $values, one associative and one numeric indexed. If you alias your data from the query, you can then fetch the associative value by name of that alias.
<?php
$query = "SELECT MAX(ID) as maxID FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values['maxID'];
Or if you want to access it numerically,
<?php
$query = "SELECT MAX(ID) FROM Table";
$result=sqlsrv_query($conn, $query);
$values = sqlsrv_fetch_array($result);
echo $values[0];
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
when I return my array by I got [{"product":"TEST_1","best_selling_product":"305"},{"product":"IPHONE 4S","best_selling_product":"108"}] , but Highcharts dont let me use string as value then how can I change it to int or float? my backend function is this
function best_selling_product(){
$sql = "SELECT product,SUM(sale_detail.amount) AS best_selling_product FROM sale_detail INNER JOIN product ON sale_detail.idproduct = product.idproduct GROUP BY sale_detail.idproduct ORDER BY SUM(sale_detail.amount) DESC LIMIT 0,5";
$result = $this->conexion->conexion->query($sql);
$array = array();
while($record = $result->fetch_array(MYSQLI_ASSOC)){
$array[] = $record;
}
return $array;
$this->conexion->cerrar();
}
In the json_encode() function, set the JSON_NUMERIC_CHECK flag.
You can either use CAST in the mysql query, or process the data in php using floatval() or intval().
For example in the mysql query:
SELECT CAST(SUM(sale_detail.amount) as UNSIGNED) AS best_selling_product FROM ...
OR with php:
while($record = $result->fetch_array(MYSQLI_ASSOC)){
$record['best_selling_product'] = floatval($record['best_selling_product']);
$array[] = $record;
}
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);
}
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.