Show selected data as array value instead of string - php

I'm trying to put data from my database into seperate arrays within another array. This works but when I'm trying to fetch the 'user_id' information, it only shows one number so it works like a string. How can I get it to work like an array and get the entire user_id?
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$return_arr = [];
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr[] = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);
echo $user[2];
This code returns 1 so it show the third number of the user_id. How can I get it to show the entire user_id like this: 111434343

You have many things in your code that's wrong:
Remove the last array item's comma
Change
$return_arr = [];
To
$return_arr = array();
3.Add:
$row_array = array()
at the begginning of all that code
At the end your code must be like this:
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$row_array = array();
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);

According to your code you should use:
echo $user['user_id'];
But the real problem is - where is $row_array initialized?!?
And even bigger problem - why use "=" inside array creation in the while ... it seems to me that "=>" would fit better, don't you think?

Related

How to retrieve values from multiple rows as a single string

I have made MySQL database with three columns tags_id,tags,user_id, it must give out all the tags with respect to the user_id given.
eg: for this link:"http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7"
Output is:
{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}
But I need my result to be in a sing string like this:
{"result":[{"tags":"Pascol","PHP",","Python"}]}
It should not be in array i want it in a single string.
Here is my php code :
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('dbConnect.php');
$user_tags = array();
foreach ($_REQUEST['user_id'] as $key => $val) {
$user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$user_ids = "'" . implode("','", $user_tags) . "'";
$sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"tags"=>$row['tags']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
what should i change in my code.?
please help me guys thank you.
Your array_push mean
Push to your array new element with $key => $value
So solution in this case is remove array_push and try
$result['tags'][] = $row['tags'];

mysql select into array twist

I have 10 rows, however when I do the following, it's only giving me the last row. Any kind of help I can get on this is great appreciated!
$query = "select * FROM `$table`.`channels` WHERE `country`='vietnam' ORDER BY `chanid`";
$result = mysql_query($query,$db) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($result)) {
$chanid = $row['chanid'];
$data[navtitle] = "$chanid - $row[title]";
$data[navurl] = "http://www.localhost.com/vietnam.php?chanid=$row[chanid]&country=$row[country]";
$data[vid_art] = "$chanart";
}
$array2=array_merge(array($array,array($data));
$JSON=json_encode($array2);
echo $JSON;
My $data array is only outputs the last row of my mysql fetch. How can I get it to pull out all 10 rows that I have?
Each time you go through the
while($row = mysql_fetch_array($result)) {
loop, you're setting $data to a new value.
This means it'll only ever contain the last row's worth of data.
Your code should look something like this.
$array2 = array();
while ($row = mysql_fetch_array($result)) {
$data = array();
$chanid = $row['chanid'];
$data['navtitle'] = "$chanid - $row[title]";
$data['navurl'] = "http://www.localhost.com/vietnam.php?chanid=$row[chanid]&country=$row[country]";
$data['vid_art'] = $chanart;
$array2[] = $data;
}
$JSON = json_encode($array2);

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

Convert Selected row to JSON - PHP

I want to convert selected result into JSON.
Here is my code:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id,user.name,user.email,ac_detail.ac_id,ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
$a=array("users"=>$usersArray);
//$row["user"]=$usersArray
array_push($row,$a);
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
?>
By executing this code it generate JSON like :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","0":{"users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}}]}
But i don't want "0"{"user::...}
How it should be (Expected Results) :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}]}
Thanks in advance
You're doing:
while($row = mysqli_fetch_assoc($sth)){
[...snip...]
array_push($row,$a);
The while line creates an array $row, which you then use parts of to create $a. You then push that $a BACK onto the original $row array. But $row is an associative array already, so the pushed $a gets key 0.
Since you're now mixing an associative array (non-numeric keys) with a numeric-keyed array (the push operation), PHP MUST add the numeric key to your pushed item: You can't have an element in an array WITHOUT a key.
Then, since JS doesn't allow actual JS arrays ([]) to have non-numeric keys, the whole thing has to get converted into an object ({}).
What you probably want is something more like:
while($row = ...) {
... build $a ...
array_push($row['users'], $a);
instead.
Why don't you in stead array_push($row,$a) try following:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id, user.name, user.email, ac_detail.ac_id, ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
// here comes the change
// $a = array("users"=>$usersArray);
// //$row["user"]=$usersArray
// array_push($row,$a);
$row['users'] = $usersArray;
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
This should work. Dont have sample data to test it.

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

Categories