Put result from mysql_query in php array - php

I want to get some results from the MySQL database and put them in a array like this:
array("value2", "value2", "value3");
I have tried this:
$models = array();
$getmodels = mysql_query("select model from cars");
while($res = mysql_fetch_array($getmodels)) {
$models[$res['model']];
}
This does not work, when i check if the model is in array i get FALSE:
in_array($_REQUEST['model'], $models))

You were supposed to give each key a value, not turning the values into the keys. Try this:
$models = array();
$getmodels = mysql_query("select model from cars");
while($res = mysql_fetch_assoc($getmodels)) {
$models[] = $res['model'];
}
This will create an array with numeric index. Each key will have the car's model as the value.

Related

How to change this array key based on this mysql result

I have this code and query also.
$id_user = $this->current_user->id;
$query_perusahaan = "SELECT
default_perusahaan.id_perusahaan,
default_perusahaan.nama_perusahaan
FROM
default_users
INNER JOIN default_user_perusahaan ON default_user_perusahaan.id_default_user = default_users.id
INNER JOIN default_perusahaan ON default_perusahaan.id = default_user_perusahaan.id_default_perusahaan
WHERE default_users.id = $id_user";
$query_perusahaans = $this->db->query($query_perusahaan)->result_array();
$list_per = array();
$list_per[null] = "Tidak memakai perusahaan";
foreach ($query_perusahaans as $item => $nama) {
$list_per[$item] = $nama;
}
print_r($list_per);
die();
This is the result :
The result what I expect is the id_perusahaan to become the array key.
What am I doing wrong? :(
Replace
$list_per[$item] = $nama;
With
$list_per[$nama['id_perusahaan']] = $nama['name_perusahaan'];
Instead of looping the array, you can use array_column
$list_per = array_column($query_perusahaans, null, "id_perusahaan");
The third argument sets the key names.
That means array_column will return the array with no specific column (null), but change the keys to "id_perusahaan".
That results in the array being associative
Or if you want the array to be flat:
$list_per = array_column($query_perusahaans, "name_perusahaan", "id_perusahaan");

Populating an array with a foreach loop?

I'm trying to populate the array for the variable $example_data. I have an array of Mass' and dates that I want to populate this array with. However I do not know how to create a new array entry for each $mass[$x] and $date[$x] that I want to store. I've tried putting a foreach loop inside the $example_data = array( but it didnt work.
This is what I want it to do, but doesn't work:
$example_data = array(
foreach($exer->results() as $ex){
$mass = $ex->Mass;
$date = $ex->Date;
array($date,$mass),
);
This is what I've tried but not sure how to complete it:
$userID = $user->data()->id;
$sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
$details = DB::getinstance()->query($sql);
$x = 1;
foreach($details->results() as $detail){
/** getting data from each record from field Mass and storing it in $mass array **/
$mass[$x] = $detail->Mass;
$date[$x] = $detail->Date;
$x++;
}
$x = 1;
$example_data = array(
array($date[$x],$mass[$x]),
/** I want it to create a new array entry for each $mass[] **/
);
It depends on the type of database you're using...
For example if you're using MySQL, it's mysqli_fetch_assoc()
You're trying to fetch a result set into an associative array but the result set itself is an associative array
try...
$sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
$details = DB::getinstance()->query($sql);
$example_data = array(
array("Mass"),
array("Date")
);
while($row = $details->fetch_assoc()) {
array_push($example_data['Mass'], $row['name_of_mass_column_in_db']);
array_push($example_data['Date'], $row['name_of_date_column_in_db']);
}
}
Basically, you can just fetch an associative array instead of populating an associative array with an associative array...

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.

Array in PHP does not work

I am trying to add array data from mysql. But only the last row details are getting added. I tried array_push also but did not work. Can any one help
$sql="SELECT * FROM server_details";
$result=mysqli_query($dbC, $sql);
while ($row = mysqli_fetch_array($result))
{
$services=array(
$row['server_name'] => array($row['server_add'] => $row['port'])
);
}
By not creating a new array in every iteration of the loop :
$sql = "SELECT * FROM server_details";
$result = mysqli_query($dbC, $sql);
$services = array();
while ($row = mysqli_fetch_array($result)) {
$services[$row['server_name']] = array($row['server_add'] => $row['port']);
}
Perhaps you're looking for this:
$services[ $row['server_name'] ] = array($row['server_add'] => $row['port']);
In the end you'll get in your $services variable an associative array, indexed by server_name column values.
If they're not unique, you should do this instead...
$services[ $row['server_name'] ][] = array($row['server_add'] => $row['port']);
This way you'll still get the same associative array, but its values will be indexed arrays; thus you won't lose any information for records with the same server_name.

Categories