php 2d array ... store mysql results in 2d array - php

I have a sql statement that returns a number of records each having 10 attributes. How can i get the data and put it into a 2D array. Currently Im doing this :
while($row1 = mysql_fetch_array($result1))
{
echo $row1[0][1]; //There is an error here
}
Is $row1 a 2D array? (It should be because Im getting n*m results). If $row1 is a 2d array then shouldn't i be able to access $row[0][1]?

mysql_fetch array returns a 1-D array, combined indexed + keyed values of one single row of data from your query results. e.g. doing
SELECT field1, field2, field3 FROM sometable
and doing a mysql_fetch_array on the result will give you an array that looks like:
$row1 = array(
0 => 'value of field1',
1 => 'value of field2',
2 => 'value of field3',
'field1' => 'value of field1'
'field2' => 'value of field2',
'field3' => 'value of field3'
)
If you want to address the entire result set as a single array, you'll have to fetch each row and add it to that array first:
$data = array();
while($row1 = mysql_fetch_array($result)) {
$data[] = $row1;
}
Which would let you do $data[0][1] (2nd field [1] of 1st record [0])

From the docs:
Fetch a result row as an associative array, a numeric array, or both
If mysql_fetch_array is recovering 1 row of data, what do you expect the second dimension to be?
First off you need to verify what sort of array you are getting, then you can understand why your keys aren't valid. Try using print_r or var_dump to examine $row1.

$row1 holds only one record at a time so it is a regular one-dimension array.
If your query returns
a b c
d e f
In the first iteration of the while loop, row1 holds a b c and in the second iteration, it holds d e f, both single-dimension arrays.

$row1 is a 1-dimensional array (a single record), in your case, holding 10 values.
As the code loops through the while statement, $row1 represents each record.
refer to the documentation here: http://ca.php.net/manual/en/function.mysql-fetch-array.php

Related

Why is array_unique not working in this situation

I have a column that contain integer values. I join all columns by doing
"SELECT GROUP_CONCAT(column) AS column"
Then I build an array doing
while ($row = $result->fetch_assoc()){
$employees[] = $row['column'];
}
print_r($employees) returns Array ( [0] => 1,2,3,4,68,25,1 )
So I want to remove the duplicate 1 and for that I use array_unique
print_r(array_unique($employees));
This still brings back Array ( [0] => 1,2,3,4,68,25,1 )
What am I doing wrong here
Solution at SQL side:
SELECT GROUP_CONCAT(DISTINCT column) AS column
if you want an ordered list:
SELECT DISTINCT column ORDER BY Column
and then store all rows by
while(...) $employees[] = $row['column'];
The problem is that you are trying to use array_unique() on a string, which won't really do anything.
You can break this string into an array by using the explode() function.
$unique = array_unique(explode(',', $employees[0]);
Alternatively, you could just check inside your loop if a value has already been put into an array using in_array().
while ($row = $result->fetch_assoc()){
if(!in_array($row['column'], $employees)) {
$employees[] = $row['column'];
}
}
Just use the array_map function. And map all value with intdiv function
$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);

PHP json_encode returning single row only

So I have an associative array $_SESSION['cart_items']) This is the current output when I print_r($_SESSION['cart_items']):
Array
(
[3] => 23
[5] => 5
[4] => 1
)
In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:
My current data:
Note that in the image above, the quantity column is different from the quantity I'm entering from a form.
So far this is the code I've tried:
$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
And this is the output:
[{"id":"5","name":"ballpen","price":"23","quantity":"13"}]
As you can see it works, though I only get a single row which should be three.
Is there something wrong with my query?
You show that the array keys in the session array match the ids in the database. implode() implodes/joins the values in the array. So you need to implode the keys:
implode(',', array_keys($_SESSION['cart_items']))
Or flip the array:
implode(',', array_flip($_SESSION['cart_items']))

Associative array not storing first result from SQL

I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.

PHP : Select from Database

thank you for reading.
I'm having a little problem with the next sentence:
$nats = mysql_query("SELECT id,name FROM reportSatus WHERE reportId = ". $_POST['id']);
$rnat = mysql_fetch_array($nats);
With print_r($rnat) :
Array(
[0] => 1
[id] => 1
[1] => Poca contaminacion
[name] => Poca contaminacion
[2] => 1
[reportId] => 1)
But in the database with the same sentence is:
id name
1 Poca contaminacion
2 Mucha contaminacion
Any idea what can it be? Thank you in advance ~
try :
echo '<table><tr><th>id</th><th>name</th></tr>';
while ($row = mysql_fetch_assoc($nats)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td></tr>";
}
echo '</table>';
From documentation
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
That's actually the way it works, if you need more rows to be returned you will need to loop throw the records
while($rnat = mysql_fetch_array($nats))
{
//print here
}

Output the data from MySQL into an 2 dimensional Array

I have record rows in MySQL as
id=0 name=tom grade=A
id=1 name=jeff grade=B
id=2 name=lisa grade=B
....... etc
Now I want to output that do a 2 dimensional array
such as
content{
{id=0
name=tom
grade=A
}
{id=1
name=jeff
grade=B}
{id=2
name=lisa
grade=B}}
$query="SELECT * FROM `user`";
$result=mysql_query($query);
$grades=array();
while($row=mysql_fetch_assoc($result)) {
...........
}
What I should put into the while loop?
mysql_fetch_assoc returns a associative array with the col name as the key and the value as the value. You have almost got everything you need to put this in another array how you want. Just put the following code in the loop to append the assoc arrays from each row into the $grades array:
$grades[] = $row;
Then you can access the values of the grades array like so:
$grades[1]['grade'] //returns the grade of row 1

Categories