Create a php array with keys and values from mysql query - php

I'm trying to store my mysql query in an array like this :
$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );
I've tried this but don't work like I need :
$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )
while ( $aRow = $sResult->fetch_assoc() )
{
$sInfo = $sResult->fetch_field();
// General output
$row_selectProduct[ $sInfo->name ] = $aRow;
}
$sResult->close();
Thx for help
EDIT :
Sorry for misunderstanding...
I'd like to name keys by the field name in database.
I try to reproduce this :
$result = array();
while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{
$row_array= array();
$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...
array_push($result,$row_array);
};

Using PDO connection functions, it's quite simple --
foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
echo $row['field_name1'].' '.$row['field_name2']; //etc...
}
Here's a good tutorial for PDO in PHP if you want more.

while ( $aRow = $sResult->fetch_assoc() )
{
foreach($aRow as $fieldname => $fieldvalue) {
$row_selectProduct[$fieldname] = $fieldvalue;
}
}
but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record
if you would like to have all results in one array you should:
$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
$results[] = $aRow;
}
if you know that there will be only one result you need only:
$result = $sResult->fetch_assoc();

Related

Put an array with foreach inside another array

I've just achieved a code where I make an array with foreach and in the same code I already have an existing array. What I want to do is to make only one array with those two results. Here is my code for the first array :
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
$res[] = $photos[$user];
}
else {
$res[] = '';
};
}
And here is my second array :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
)
);}
If you have any tips, any comment or even a question (if I wasn't clear enough for you), just ask me ! Thanks !
Edit :
What I want to make is an array of this type :
[{"name":"usera","publisher":"Jeana","image":"urla",""photouser","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","photouser","url2b"}]
You need to use the key you have in the first portion:
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
# Set the username--vvvevvvvv
foreach($restest as $username => $user) {
# Store the username as the key here for reference later
$res[$username] = (isset($photos[$user]))? $photos[$user] : '';
}
In this array, reference the username from the other array:
while($row = mysqli_fetch_array($result)){
$res2[] = array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
# Using the username as the key name, see if it $res has a saved value
"photouser" => (isset($res[$row['username']]))? $res[$row['username']] : false
);
}
I finally achieve what I wanted to do, by using a replacement technic :
With the foreach loop, I've created an array with the parameter profilepic, on the other array, I've created another parameter with a default value, then I replaced it.
My code : First my foreach loop :
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
array_push($res1, array(
"profilepic"=>$photos[$user]));
}
else {
array_push($res1, array(
"profilepic"=>'defaultvalue'));;
};
}
and then I changed :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
"profilepic"=>'defaultvalue'
)
);}
And finally I replaced it by :
$res = array_replace_recursive($res2,$res1);
So my final array with echo json_encode($res) is:
[{"name":"usera","publisher":"Jeana","image":"urla",""profilepic","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","profilepic","defaultvalue"}]

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

Dynamic Content in PHP array

This should be a quick one.
I'm pulling a list of id's and I need to place them in an array.
Here is my php code to get the list of id's
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
echo $insta_id;
};
This echo's a list of id's that looks like this: '146176036','136514942',
Now I want to put that list into an array. So i tried something like this:
$y = array($insta_id);
However that isn't working. Any suggestions?
$y = array();
while ($row = mysql_fetch_assoc($get_archives)) {
$y[] = $row['insta_id'];
}
$myArray = array();
$get_archives = mysql_query("SELECT * FROM archive WHERE user = '$email' ");
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id = $row['insta_id'];
$insta_id = "'" . $insta_id."',";
$myArray[] =$insta_id;
};
did you mean like this: ?
$insta_id=array();
while ($row = mysql_fetch_assoc($get_archives)) {
$insta_id[] = $row['insta_id'];
}
Create an array, and push the values into it:
$values = array();
while ( $row = mysql_fetch_assoc( $get_archives ) ) {
array_push( $values, $row['insta_id'] );
}

Creating Structured array by Recursive function

I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}

Categories