I have a list of users in my table. How would I go about taking that list and returning it as one PHP variable with each user name separated by a comma?
You could generate a comma-separated list with a query:
SELECT GROUP_CONCAT(username) FROM MyTable
Or else you could fetch rows and join them in PHP:
$sql = "SELECT username FROM MyTable";
$stmt = $pdo->query($sql);
$users = array();
while ($username = $stmt->fetchColumn()) {
$users[] = $username;
}
$userlist = join(",", $users);
You would fetch the list from the database, store it in an array, then implode it.
The best way I was able to figure this out was by storing the results from each col, or field, and then echoing the implode:
$result = mysqli_query($conn, $sql) //store the result
$cols = array(); //instantiate an array
while($col = mysqli_fetch_array($result)) {
$cols[] = $col['username']; //step through results and save each username in array
}
echo implode(",",$cols); //turn the array into a comma separated string and echo it
This took me a while to figure out exactly how to do this. Hope it helps!
Related
I have two tables is sql 1) friends_details and 2) user_info.
Now using the below query am getting the list of friends of that particular using $number = is coming from app
$sql = "select friends from user_info WHERE user_number ='$number' ";;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
now $emparray have names of friends in String fromat. Now i want to pass this array into another query so that i can find the details of these friends. And Can't find the way to do. I have tried this code.
$friendsArray2 = "'" .implode("','", $emparray ) . "'";
$query120 = "SELECT * FROM friends_deataisl WHERE name IN ( $friendsArray2 )";
echo $query120;
and the result of echo $query120 is SELECT * FROM friends_deatails WHERE name IN ( 'Array','Array' )
So this means values are not going in the query. Any help would be appreciated.
And i have already checked $emparray is not empty it contains the name that means first query is right but the problem is in second query.
$emparray is a 2-dimensional array, not an array of strings, because $row in the first loop is an associative array.
You need to change the first loop to do:
$emparray[] = $row['friends'];
But you could just combine the two queries into a JOIN:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON fd.name = ui.friends
WHERE ui.user_number = '$number'
Also, the column name friends makes me suspect that this is a comma-separated list of names. Using = or IN won't work with that -- it will try to match the entire list with friend_details.name. It's best to normalize your database so you don't have lists in a column. If you can't fix that, you need to use FIND_IN_SET to join the tables:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON FIND_IN_SET(fd.name, ui.friends)
WHERE ui.user_number = '$number'
And in your original code, you'll need to explode $row['friends']:
$emparray = array_merge($emparray, explode(',', $row['friends']));
I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}
I want to convert my query result to two dimensional array the query is
SELECT c.name,c.mobile_number,t.service_time
FROM CUSTOMER AS c
JOIN TRANSACTION AS t ON c.id = t.customer_id
WHERE t.service_date = '$date'
AND employee_id = '$employee_id
I get name(varchar),mobile num(int) and time which is time format. I wrote some code but it is not working:
$results = array();
echo $num_fields=mysqli_num_fields($array1);
echo $num_rows=mysqli_num_rows($array1);
while($line = mysqli_fetch_array($array1))
{
for($i=0;$i<$num_rows;$i++)
{
for($j=0;$j<$num_fields;$j++)
{
$results[$i][$j]=$line[$i][$j];
}
}
}
The result I am getting is:
[["k ","a ","r "],["9 ","8 ","7 "],["0 ","2 ",": "]]
The output contains only first characters that to one. I want each row of two dimensional array to have row of my query result.
You can just add the result to a new array and change mysqli_fetch_array to mysqli_fetch_row:
$results = array();
while ($line = mysqli_fetch_row($array1))
{
$results[] = $line;
}
Alternatively you can use mysqli_fetch_assoc() to make for an associative array (e.g. $results[0]['name'] will be the name column of the first row).
Edit
If there are duplicate column names you can use aliases:
SELECT one.name AS one_name, two.name AS two_name FROM one INNER JOIN two USING ...
The associative array will then have $result[0]['one_name'] and $result[0]['two_name'].
try this:
while($line = mysqli_fetch_row($array1))
{
array_push($result, $line);
}
This should do it
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$result = mysqli_query($con, "SELECT * FROM .....");
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($con, $result)){
array_push($rows, $row);
}
mysqli_free_result($result);
}
var_dump($rows);
I'm trying to make an associate array to loop through.
Both values I want come from query2 but the second one is a column with numbers from 1-40. When I normally make an combine_array it says that the arrays are not equally long as PHP treats the for example number 10 as two values somehow. But I want to connect the numbers with the names equally.
I've tried the foreach loop but that didn't work out so far.
How can I make such an array?
PS. I need the array to combine with the values from $query to get the Artikelnaam values from another table.
$query = "SELECT * FROM orders WHERE klantnummer = '{$_SESSION['userid']}'";
$query2 ="SELECT Artikelnaam, Artikelnummer FROM products";
$stmt = $db->prepare($query);
$stmt2 = $db->prepare($query2);
$stmt->execute();
$stmt2->execute();
while($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$combined = "";
foreach($row["Artikelnummer"] as $row['Artikelnummer'] => $row['Artikelnaam']) {
$combined = $row['Artikelnummer'] . $row['Artikelnaam'] . ",";
echo $combined;
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"];