Php array from sql result - php

How can i create an array from the result? I would like to use the array in a mysql IN() query.
//$array = array();
$get_subscategoria = mysqli_query($kapcs, "SELECT kat_id FROM termek_kategoria WHERE kat_parent = '$id'");
if(mysqli_num_rows($get_subscategoria) > 0 )
{
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
}
//print_r( $array );
Now, this code gives back 4 row ID, that works okay. I would like an array with these ID-s, like 1,2,3,4.

Instead of:
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
use:
$array = mysqli_fetch_assoc($get_subscategoria);

while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
$array[] = $sub_kat['kat_id'];
}
echo implode(",",$array);
it give a result like 1,2,3,4

For MySQL, also you can use group_concat, only gives you one record:
SELECT GROUP_CONCAT(kat_id) AS kat_id
FROM termek_kategoria
WHERE kat_parent = '$id'
GROUP BY kat_parent

Related

php returning value from mysql 2 times

I am using the code below to return value from sql but the value is displayed 2 times.
$cc=mysqli_connect($server,$user,$pass);
mysqli_select_db($cc,$database);
$sql = "SELECT b_id FROM ``ub_per`` WHERE ``b_email`` = '$mail'";
$res = mysqli_query($cc,$sql);
$row = mysqli_fetch_array($res);
foreach($row as $value){
echo($value);
}
I think the answer is a little more complex than that.
So the row $row = mysqli_fetch_array($res); will return an array, I think if you check there will be 2 items in it.
Looking like this
$row[0] = id;
$row['b_id'] = id;
now you do
foreach($row as $value){
echo($value);
}
So will echo id out twice.
Use
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
To get you what you want.
It is because query gives you 2 results(rows).
Try:
echo '<pre>';
print_r($row);
And you will see if there are more than 1 rows in results.

How to fetch all the matched rows from a Mysql table in a PHP array

I am trying to get the matched rows from a table and save it in a Global Array so that I can use it in different functions.
But when I do print_r of that array it shows only last row.
Here is my code
function setCampoFeed()
{
echo $sql = "SELECT campofeed.tag,campofeed.registro,campofeed.valor FROM campofeed ".
"INNER JOIN registrofeed ON registrofeed.id = campofeed.registro ".
"WHERE registrofeed.feed='".$this->idFeed."'";
$result= $this->localDb->execute($sql);
$this->campoFeed= mysql_fetch_array($result))
}
So here campoFeed is the array that should have all the rows of the match, but now its just having the last row.
Thanks in advance
Use
$this->campoFeed[] = mysql_fetch_array($result);"
insted of
$this->campoFeed= mysql_fetch_array($result);
You will get all data in array
Try this one if it works for you..
$resultArray = array();
$campoFeed = array();
$resultArray = mysql_fetch_array($result);
foreach($resultArray as $key => $value){
$campoFeed[$key] = $value;
}
print_r($campoFeed);
Use this
$mergedArray=array();
while($data= mysql_fetch_array($result)) {
$final_array = unserialize($data['data']);
$mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);

How to combine two or more mysql array in one

I have two table that has multiple rows. I want to combine those two tables rows into one long array which will be identified as one array
I wrote this code
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row){
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
$data[] = $users_all;
}
echo json_encode($data);
It makes duplicate arrays doesn't right...
That's how my result show
[{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
},
{
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}]
please help me make it just one long array
I would like to see the output looks like this
{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}
look at this,i have taken example values, it is working fine as you wanted
$arr=array(array("abc"=>"1","def"=>"2"),array("abcc"=>"11","deff"=>"22"));
echo json_encode($arr);
$final = array();
foreach($arr as $item) {
$final = array_merge($final, $item);
}
print_r($final);
output
[{"abc":"1","def":"2"},{"abcc":"11","deff":"22"}]//json_array
Array ( [abc] => 1 [def] => 2 [abcc] => 11 [deff] => 22 )//final array
UPDATE
json_encode the final array and you'll get the desired result
echo json_encode($final);
output
{"abc":"1","def":"2","abcc":"11","deff":"22"}
Untested:
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row) {
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
foreach($users_all as $user)
$data[] = $user;
}
}
echo json_encode($data);
// when you use json_decode use the 'true' flag as in
// $decodedJson = json_decode($json, true);
Merge them before you json_encode them:
$data[] = $posts_row;
$data2[] = $users_all;
$result = array_merge($data,$data2);
echo json_encode($result);

Cannot echo result from a query

I have a class, where i have a function with the following query.
public function count_weight() {
$id = $_SESSION['id'];
$query = $this->db->prepare("SELECT sum( weight ) FROM `fish` WHERE `user_id` = '".$_SESSION['id']."'");
try {
$query->execute();
} catch(PDOException $e) {
die($e->getMessage());
}
return $query->fetchAll();
}
I want to echo out this result on my index-page. Right now it looks like this:
$weight = $users->count_weight();
echo $weight;
Which obviously doesn't work, it only prints out "arraykg".
Any suggestions?
You can't print an array like that. e.g.
$arr = array(1,2,3);
echo $arr;
is going output the literal text Array, because you're using the array in a string context. If you want to print the CONTENTS of the array, you'll need to do something with it, e.g.
echo implode(',', $arr); // prints: 1,2,3
or
print_r($array); // debug dump out of the array
Try this for example:
$weight = $users->count_weight();
foreach($weight as $w)
{
echo($w['id']):
}
$query->fetchAll(); will return an array. Use var_dump() to analyze the array and adjust your variable declaration accordingly.
echo "<pre>";
print_r($weight);
echo "</pre>";
Assuming $weight actually contains data and is not a resource.
$weight is an array of the row that it retrieved. You'll need to echo out that column
echo $weight['weight'];
This may or may not work because of the query. Try changing the query to this:
$query = $this->db->prepare("SELECT sum( weight ) AS weight FROM `fish` WHERE `user_id` = '".$_SESSION['id']."'");

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++
}

Categories