Convert query result to two dimensional array - php

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);

Related

Creating json from sql query with an additional key/value pair using PHP

Disclaimer: I'm fairly new to php.
I am trying to create an array out of a query witch could return multiple results. Additionally, I am doing a distance calculation and adding that value to the array, creating a json string, then returning it to my javascript.
I can create the array with the data from the database, and insert the additional value into the array, and return it, but when I try with a query witch returns more than one result, I'm only getting the last result back, because the array is being over written. I've tried to the array_merge function, but I'm still only getting the last one back.
Here is what I have so far:
$positionquery = "select d.code, d.lon, d.lat from table1 as d where d.lon <> 0 and d.lat <> 0 and d.brand = 'THE_BRAND'";
$results = mysql_query($positionquery) or die ('Query Failed" ' . mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results)){
$locations = $row;
$tempdistance = distance($lat, $lon, $locations['lat'], $locations['lon'], 'M');
if($tempdistance <= 150){
$secondquery = 'SELECT * FROM table1 as d left join table2 as p on p.dealer_name = d.dealer_name left join table3 as o on o.retailercode = d.cicode where d.cicode ="'.$locations['cicode'].'"';
$queryResults = mysql_query($secondquery) or die('Query Failed ' . mysql_error());
$tempArray = mysql_fetch_assoc($queryResults);
$tempArray['distance'] = $tempdistance;
$returnArray = array_merge($returnArray,$tempArray);
}
}
echo json_encode($returnArray);
}
Any help would be greatly appreciated.
You're not creating an array of results, you're overwriting the $returnArray variable with each row of the results. It should be:
$returnArray = array();
while ($row = mysql_fetch_assoc($results)) {
...
$returnArray[] = $tempArray;
}
echo json_encode($returnArray);

PHP/MySQL: fetch one result

This is my database:
This is the query:
SELECT * FROM users
Now when I do this:
$query = $connection->query($_GET['query']); // SELECT * FROM users
print_r($query->fetch_assoc());
I get this as output:
Array (
[id] => 3
[username] => karel )
Why does it not output id 4 and username ccscs?
When I a while loop:
while($row = $query->fetch_assoc()){
print_r($row);
}
This is happening because you don't give any order to your query so it automatically get first record. If you want to return last record you can order by id desc as follow
SELECT * FROM users ORDER BY id DESC
If you instead need to retrieve all records you will need to loop throw your records
while($row = $query->fetch_assoc())
{
print_r($row);
}
Based on new op info i would not fetch twice but one as follow
$fields = array();
while($row = $query->fetch_assoc())
{
print_r($row);
$fields[] = $row;
}
fetch_assoc() retrieves a single row from a result set. See here.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
You should use something like this :
while($row = $query->fetch_assoc()){
print_r($row);
}
That's because fetch_assoc() just fetches one row.
To get each row you can do it like this:
while($row = $query->fetch_assoc()){
print_r($row);
}

display all cells in a mysql column

I need all values from a table column put into an assoc array. I am having trouble finding the answer.
the table is only six rows deep.
example:
|--id--|--name--|--A--|--B--|--C--|
|--01--|--xl33--| 1.30| 2.45| 4.40|
i would like to get an assoc array for column B
name[xl33]=2.45
name[xl34]=....and so on
The trick is that the form will tell the script which column to fetch. A,B,C,D,E,F OR G
I know i could re-format the table and accomplish what i want but I need it structured the way i have it.( i have left out some columns for simplicity)
function return_column($letter){
$result = mysql_query("SELECT name, $letter FROM example") or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) {
$return[$row['name']] = $row[$letter];
}
return $return;
}
$results = return_column('A');
print_r($results);
Something like :
$col = 'B';
$name = array();
$result = mysql_query("SELECT * FROM table") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name[$row['name']] = $row[$col];
}
This creates an array $name and uses the name column as the key and the $col column for the value ...
You are looking for the mysql_fetch_assoc() function.
Example/
$query = $this->query($YOUR_QUERY);
$returnMap = array();
while ($row = mysql_fetch_assoc($query)) { array_push($returnMap, $row); }
Use mysql_fetch_assoc — Fetch a result row as an associative array.
while ($row = mysql_fetch_assoc($result)) {
$data[$row["column1"]]= $row["column2"];
..............
.........
}

JOIN query only returning 1st row

I'm trying to retrieve multiple rows from joining two tables where store.itemid = item_list.id.
$query = "SELECT s.price, il.*
FROM store s LEFT JOIN item_list il ON s.itemid = il.id";
I then have:
if($result = $conn->($query)) {
$array = $result->fetch_array(MYSQLI_ASSOC);
}
With my current code, the query is only retrieving the first row from the 'store' table. I have made certain that there should definitely be more than one row to return.
print_r($array) shows:
Array ( [price] => 400 [id] => 5 [name] => Computer )
That's because you are only running fetch_array() once. You probably need to run it in a loop, e.g.:
if ($result = $conn->query($query)) {
while ($array = $result->fetch_array(MYSQLI_ASSOC)) {
// do something with $array
}
}
instead of this:
$array = $result->fetch_array(MYSQLI_ASSOC);
use this:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
//put your code here!
}

Create Comma Seperated List from MySQL PHP

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!

Categories