Select one field separated by comma [duplicate] - php

This question already has answers here:
Closed 10 years ago.
I want to select one column values separated by commas from the below table.
username
--------
A
B
C
D
I want the result like A,B,C,D.

you can do it directly on your query. use GROUP_CONCAT for this,
SELECT GROUP_CONCAT(`username`)
FROM tableName

Use this code:
$qry="select username from tableName ";
$exe=mysql_query($qry);
while($r=mysql_fetch_array($exe))
{
$userName .=$r['username'].",";
}
$userName =substr($userName,0,-1);
echo $userName;

Try like this:
$sql = 'SELECT username FROM table_name';
$query = mysql_query($sql);
$csv = array();
while($row = mysql_fetch_array($query)) {
$csv[] = $row['username'];
}
echo implode(',', $csv);

Related

mysql order by last value in table separated by comma [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 3 years ago.
so I'll try to be short,
I'm trying to ORDER BY ID from table whose values are separated by commas.
Here's an Image:
I want them to be ordered like this when displayed: 34, 40, 33, 0.
here's my code:
/// movie
$myuserid = $_SESSION['user_id'];
$mymovies = "SELECT p_movies FROM user_details WHERE user_id='$myuserid' ";
$mymoviesresult = mysqli_query($_db,$mymovies);
$mymovie = mysqli_fetch_array($mymoviesresult);
/// movie
$mypurchases = $mymovie['p_movies'];
$sql = "SELECT * FROM movies WHERE find_in_set(id, '$mypurchases') > 0";
$res_data = mysqli_query($_db,$sql);
if($res_data = mysqli_query($_db, $sql)){
if(mysqli_num_rows($res_data) > 0){
while($row = mysqli_fetch_array($res_data)){ include 'movies/appearance.php'; }}}
I tried to add ORDER BY DESC and ASC, it doesn't work. Is it possible to order results in the manner stated above?
Don't know how to explain it better, sorry for my English.
Since FIND_IN_SET() returns the position in the list, you can use that for your ordering.
There's also no need to use two queries, you can join the tables. And you should use a prepared statement to prevent SQL injection.
$stmt = $_db->prepare("
SELECT m.*
FROM movies AS m
JOIN user_details AS d ON FIND_IN_SET(m.id, d.p_movies)
WHERE d.user_id = ?
ORDER BY FIND_IN_SET(m.id, d.p_movies) DESC") or die($_db->error);
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
include 'movies/appearance.php';
}
}

Using PHP what is the best way to get multiple rows in one MySQL query? [duplicate]

This question already has answers here:
MySQL PHP - SELECT WHERE id = array()? [duplicate]
(6 answers)
Closed 8 years ago.
Which is the best way to Get multiple rows in one MySQL query.
I have an array of IDs:
$id_array = array('34','341','342','334','344','354','3234','33234','3234','3234');
I would like to get the title associated with those id's from my mysql database.
I have two approaches:
1) example:
foreach($id_array as $id){
$query = mysqli_query($con, "SELECT title FROM content WHERE id = '$id'");
$id_db = mysqli_fetch_row($query);
echo $id_db['title'];
}
2) example:
$query = mysqli_query($con, "SELECT title FROM content WHERE id = '$id_array[1]' AND id = '$id_array[2]' AND id = '$id_array[3]' AND 'id = $id_array[4]' AND id = '$id_array[5]'");
while($result = mysqli_fetch_assoc($query)){
echo $result['title'];
}
I am working on high load site and would like to use the best solution.
The above code isn't 100% complete, it is just a raw implementation of the idea.
The array elements can be from 1 to 1k in count.
What about this solution ?
$ids = implode(',',array_map('intval',$id_array));
$query = mysqli_query($con, "SELECT title FROM content WHERE id IN ($ids)");
// ..
Use mysql in array method man.
If you want get titles for ids that are in array:
$db = new mysqli('server', 'user', 'password', 'db');
$stmt = $db->prepare('select title form content where id = ?');
$stmt->bind_param('i', $i);
$stmt->bind_result($title);
$titles = array();
foreach($id_array as $a) {
$i = $a;
$stmt->execute();
array_push($titles, $title);
}

MYSQLI query to get one single result [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 4 years ago.
I need to get only the id of member who's username is X from the mysql database.
Can this only be done with a while loop or is there any other way around this?
What I'm thinking of is something like:
$id = mysqli_query($con,'SELECT id FROM membrs WHERE username = '$username' LIMIT 1)
Thanks,
You can use:
mysqli_fetch_array();
// For Instance
$id_get = mysqli_query($con, "SELECT id FROM membrs WHERE username='$username' LIMIT 1");
$id = mysqli_fetch_array($id_get);
echo $id['id']; // This will echo the ID of that user
// What I use is the following for my site:
$user_get = mysqli_query($con, "SELECT * FROM members WHERE username='$username'");
$user = mysqli_fetch_array($user);
echo $user['username']; // This will echo the Username
echo $user['fname']; // This will echo their first name (I used this for a dashboard)
without while loop we can do it by the following code, if you are selecting more than 1 record you need to loop it
$row = mysqli_fetch_array($id);
echo $row['id'];

Counting each username in a table [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MYSQL COUNT GROUP BY question
$query = "SELECT * FROM product_id_1";
$result = mysql_query($query);
while( $record = mysql_fetch_array($result) ){
$array[] = $record['username'];
$unique_array = array_unique($array);
}
foreach( $unique_array as $list ){
echo $list.'<br/>';
}
Greeting,
I'm stuck trying to figure out how to apply array_count_unique(). Reason is I need to find out the count of each individual user in the table, i.e how many times adam appears and how many times abcd appears.
UPDATE
This is what I've done according to you guys's suggestion:
$query = 'SELECT username, COUNT(*) AS username_count FROM product_id_1 GROUP BY username';
$result = mysql_query($query);
while ($record = mysql_fetch_object($result)) {
echo $record->username;
echo $record->username_count;
}
This is exactly why we have RDBMS and SQL:
SELECT COUNT(1) AS username_count, username
FROM
product_id_1
GROUP BY
username

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories