Make array with arrays from a mysql query - php

Working on a e-shop, i must read from the DB the products that have productpack not null.
productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .
I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).
function p_productpacks(){
$productpacks = array();
$pack = array();
$q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');
while($p = mysql_fetch_object($q)){
$pack = explode(",", $p);
$productpacks[] = $pack;
}
return $productpacks;
}

You need to create an array otherwise, you're overwriting existing packs:
$pack = explode(",", $p->productpack);
$productpacks[] = $pack;
For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).

You can get all productpacks in a CSV array using:
$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
FROM products WHERE productpack <> '' ");
if ($result) {
$row = mysql_fetch_row($result);
$productpacks_as_CSV_string = $row['productpacks'];
}
That way you only need to get one row out of the database, saving lots of time.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:
$pack=explode(',',$p->productpack);
$productpacks[]=$pack
Or, to use a good old array instead:
while ($p = mysql_query($q))
{
$pack = explode(",", $p['productpack']);
$productpacks[] = $pack;
}

Related

Create array in PHP from mysql

I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. I have a query like so:
$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
$description = $row['description'];
$description = strtoupper($description);
$id = $row['id'];
}
I want it to create an array like so:
$v[1] = "Myarray1";
I have tried this but it does not work:
$v[ $row['id']] = $row;
Do I have to query like this:
while( $row = mysql_fetch_assoc( $result)){}
and if I do, how I do create the array as I need it?
Many thanks in advance
At no point are you creating an array here. In your loop you are simply modifying some variables that in the context you posted I cannot reason on.
If all you need, no data filtering whatsoever this will do:
$list = Array();
while( $row = mysqli_fetch_array($result) ) {
$list[] = $row;
}
[] basically 'appends' in PHP, it is an ugly mechanism but it works.
If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]]
I'm not exactly sure of the end result you're looking for. But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. I think this example will help:
while (($row = mysqli_fetch_assoc($result))) {
$v[$row['id']] = $row;
}
$v[1]['description'] is the data in the column description for the record with an id=1

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
Note: If you use `array_push()` to add one element to the array it's
better to use$array[] = because in that way there is no overhead of
calling a function.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

php - dynamic mysql_query in for loop from url array

I've looked for something similar on stack but nothing exactly as this.
I (think I) need to generate a unique MySQL query inside a loop as each iteration needs to look up a different table. the loop is from an exploded $_GET array.
The problem is creating a differently named mysql query based on the loop iteration. I've done it where the $var name is different but it doesn't work, I think because it is a string not a variable?
Any help appreciated
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
for ($i=0; $i<$tempCount; $i++)
{
/*'normal' database lookup
$check = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checks = array();
while ($row = mysql_fetch_assoc($check)) {
$checks[] = $row;
}*/
//here's where I'm trying to build a 'dynamic' lookup for each loop iteration
$checkTemp=$check.$temps[$i];
$checkTempArray=$check.$temps[$i].'Array';
$checkTemp = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checkTempArray = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$checkTempArray[] = $row;
}
}
If I understand correctly you're trying to SELECT * from all tables seperated by , in the $_GET["temps"]
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
$allResults = array();
for ($i=0; $i<$tempCount; $i++)
{
$checkTemp = mysql_query("SELECT * FROM _db_".mysql_real_escape_string($temps[$i]));
$allResults[$temps[$i]] = array();
while ($row = mysql_fetch_assoc($checkTemp))
{
$allResults[$temps[$i]][] = $row;
}
}
// Now for example $allResults["john"][3] contains the fourth row in the table _db_john
print_r($allResults["sally"][2]); // print the third row in _db_sally
Seems like a typo in your code
$checkTemp = mysql_query("SELECT * FROM db".$temp[$i]."");
either use
$temps[$i] or just $temp
$temp[$i] doesn't makes any sense
so your query should be instead
$checkTemp = mysql_query("SELECT * FROM db".$temps[$i]."");
EDIT:
for your array part you can use
$$temp = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$$temp[] = $row;
}

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

Creating one big array from two different arrays by comparing values PHP

I have a MySQL table with reports. Fetching my reports is used by function:
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
return $array;
}
which creates an multidimensional array.
[latitudes in MySQL are stored like 25.33236645, 23.2665666 etc...]
I have a different array:
$array_lat = array(25.5,23.1,45.2);
So, I would like to know if it is possible to get through array values of $array_lat with checking the match with values from multidimensional array created by function fillItByRoute() and storing values of function fillItByRoute() in new array?
One more time, shortly:
There are different values in $array_lat;
I want to check function fillItByRoute() with input of $array_lat
Results, which suit have to be stored in new array.
The new array should be with values (using values of my $array_lat): 25.5666332, 25.511433, 23.1233, 23.11444, 23.1, 45.269...etc, could be even hundreds of items.
Is it possible to do something like that?
Thank you very much!
I think you want something like this. It iterates through your array_lat and compares it to a value from SQL. I'm not entirely sure what you want to do with the comparison but you should put it in the if statement from the second function. If you want a new array it looks like you understand how to create those but let me know if this is too ambiguous.
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
return $array;
function compareArrToSql($array_lat){
for($curr_lat = 0; $curr_lat<count($array_lat); $curr_lat++){
$sql_val = fillItByRoute($array_lat[$curr_lat]);
if($array_lat[$curr_lat]==$sql_val){
}
}
}
If my assumption about what you meant is correct, this is what you are after:
function fillItByRoute($lat){
global $db;
$array = array(array());
$result = $db->query("SELECT * FROM reports WHERE latitude LIKE '$lat%' ORDER BY datetime_view");
while ($row = $db->fetch_array($result)){
$latitude = number_format((float)$row['latitude'], 2, '.', '');
if (in_array($latitude,$lat)) {
$array[$int][1] = "Desc";
$array[$int][2] = $row['latitude'];
}
}
return $array;
}

Categories