I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}
Related
I am developing a webservice for and android app the webservice is in PHP fetching data from a MySQL database ... The problem that I am having is that some of the projects have multiple details but my code is only fetching one detail for every project. I am getting the data in JSON format.
You can check this Here
Here is my code
function requiredData(){
$db = $this->dbConnection();
//$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$sql = "SELECT * FROM projects";
$queryResult = $db->query($sql);
if($queryResult->num_rows > 0){
while($row = $queryResult->fetch_assoc()){
$pid = $row['project_id'];
$detailsql = "SELECT * FROM project_details WHERE project_id=$pid";
$sqlResult = $db->query($detailsql);
if($sqlResult->num_rows > 0){
while ($d = $sqlResult->fetch_assoc()){
$r = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
}
$results[$row['project_name']] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"project_work_details" => $r
);
}
}
return $results;
}
Thanks in advance for your help
The issue is in the second while loop. You are assigning array to $r, and $r value overwrites every time.
So, I am assigning now array to an other array, So it will become 2 dimensional array, like this;
while ($d = $sqlResult->fetch_assoc()){
$r[] = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
Now you can use $r, it will have multiple details of the project.
I would like to include a php function into the query loop which simply outputs all rows from a table.
This function would return another query counting the rows of individual users and would be encoded together with the first query.
The function works, if I echo the userId variable I get it right, but for a reason the count query returns null.
I could use some help, thanks!
<?php
include_once 'includes/db_connect.php';
$query = "SELECT * FROM UPLOADS";
//Creating resonse json array, with another array inside
$jsonResponse = array( "info" =>array() );
if($result = mysqli_query($mysqli, $query)) {
while($row = mysqli_fetch_assoc($result)){
$jsonRow = array(
'user' => $row['USER'],
'userId' => $row['USERID'],
'filename' => $row['FILENAME'],
'description' => $row['DESCRIPTION'],
'location' => $row['LOCATION'],
'address' => $row['ADDRESS'],
'likes' => $row['LIKES'],
'city' => $row['CITY'],
'lat' => $row['LAT'],
'lng' => $row['LNG'],
'countPost' => countUserPosts($row['USERID'])
);
//adding the $jsonRow array to the end of the "users" array as key/value
array_push($jsonResponse["info"], $jsonRow);
}
}
//encoding to json for the app
echo json_encode($jsonResponse);
function countUserPosts($userId){
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}
?>
Try to inject the mysqli object inside your function paramater:
function countUserPosts($userId, $mysqli){
// ^ this one so it won't be out of scope.
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}
I have this array:
$arrUsers = array(
array('username' => 'admin', 'password' => 'admin123')
);
I just want to build a similar copy of this array using data from PDO MySQL Table, with foreach.. I've tried this, but doesn't work
$arrUsers = array();
foreach ($users as $i){
array_push($arrUsers, array('username' => $i['username'], 'password' => $i['password']));
}
returns a different array structure..
--EDITED:
MY PDO CODE
$sql_buscaUsuarios = "SELECT username, password FROM users";
try{
$query_buscaUsuarios = $conecta->prepare($sql_buscaUsuarios);
$query_buscaUsuarios -> execute();
$usuarios = $query_buscaUsuarios->fetch(PDO::FETCH_OBJ);
}
catch(PDOexception $erro_buscaEndereco){
echo 'er2'.$erro_buscaEndereco->getMessage();
}
I have an php array with presentation as follow:-
<?php
$ads = array();
$ads [] = array(
'name' => 'Apple',
'duration' => '3',
'price' => "$5"
);
$ads [] = array(
'name' => 'Orange',
'duration' => '2',
'price' => "$10"
);
$ads [] = array(
'name' => 'Banana',
'duration' => '5',
'price' => "$6"
);
and then, I would like to replace the static data with dynamic data from database:-
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
while($record = mysql_fetch_array($result))
{
$fruit_id = $record['fruit_id'];
$fruit_name = $record['fruit_name '];
$fruit_price= $record['fruit_price'];
$fruit_duration= $record_approve['fruit_duration'];
}
Actually, how shall I combine the 2 presentations together? Thanks!
If you want to get a similar structure as the one that you have in the first example, you can modify your second to create a new array and append it to an existing $ads array.
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array(
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']);
}
iteration over result can be modified (provided only the required attributes are fetched in the query)
$fruit = array();
while($record = mysql_fetch_array($result))
{
$fruit[] = $record;
}
may be you could use array_merge
$result = array();
$result = array_merge($ads,$fruit);
So, you want to populate your "ads" array with information from the database? It seems fairly counterintuitive seeing as mysql_fetch_array already returns a perfectly adequate associative array, but here you go:
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array (
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']
);
}
If
the initial array is not just an example, but default data that you might overwrite with the db data, and
the fruit name is unique (a primary key of sorts)
then you should set the array key of the main array to that of the fruit name, so that if the db has a different value, it will automatically get overwritten but otherwise left alone. Like so:
$ads ['Apple'] = array(
'duration' => '3',
'price' => "$5"
);
$ads ['Orange'] = array(
'duration' => '2',
'price' => "$10"
);
$ads ['Banana'] = array(
'duration' => '5',
'price' => "$6"
);
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[$record['fruit_name']]['price'] = $record['fruit_price'];
$ads[$record['fruit_name']]['duration'] = $record['fruit_duration'];
}
Now, if 'Apple' is in the db, the price and duration get overwritten, but otherwise, it stays where you set it before the query.
You could go a step further and have both the price and duration returned by the query checked for an empty value (Null, "", 0), and only set the value if it is not empty, etc. But that is more a of business logic decision.
$feeds = array();
$query = "SELECT * FROM actions WHERE user_id = '$user_id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("feed" => array($info['ID'] => $user_id));
}
$query = "SELECT * FROM follows WHERE user_id = '$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("follow" => $info['user_id']);
}
I would like to sort that $feeds array in date format (Y-m-d H:i:s) using [$info['date']] key
How can i do that ?
thanks
EDIT:
example of what i want to see as result is
$feeds = array(
0 => array(
'<date>' => array("feed" => array("feed_id" => "user_id"));
),
1 => array(
'<date>' => array("follow" => "user_id" );
),
);
I want to group/sort them in DATE key and do sth depends on if it is FEED or FOLLOW
The best way is to do it in database (faster)!
But if you want do it in PHP, your need uksort (for sorting) + foreach (for grouping) I think