Mysqli fetching data from two columns - php

I have 3 tables users(id,name,etc..), trips(id,user_id,from,to,destionation) , vactions(id,user_id,from,to,destionation).
I use mysqli and i can not figure out how to do this
I need to fetch this table like this
Array
(
[0] => Array
(
[id] => 1
[current_status] => 0
[username] => user1
[fullname] => Eric Norman
[trips] = > Array
(
[0] => Array
(
[date_from] = 02/06/14
[date_to] = 05/06/14
[destination] = "Grece"
)
[vacations] = >
)
[1] => Array
(
[id] => 2
[current_status] => 0
[username] => user2
[fullname] => Joe Grey
[trips] = > Array
(
[0] => Array
(
[date_from] = 02/06/14
[date_to] = 05/06/14
[destination] = "Grece"
)
[vacations] = >
)
)
I've tried with left join but i doesn't work and my code now is only for users :
conn = new mysqli($host,$user,$password,$db);
$result = mysqli_query($conn, "SELECT id, current_status, username, CONCAT(first_name,' ',last_name) as fullname FROM user");
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}

I think the best way is to get all users, then use a foreach to get all trips and vacations.
Because I'm not sure you can obtain this kind of array result using a simple SQL query, I think ou need an ORM.
$users = getAllUsers();
foreach($users as $user){
$user['trips'] = getTripsByUserId($user['id']);
$user['vacations'] = getVacationsByUserId($user['id']);
}
Of course you need to code the 3 methods "getAllUsers" ; "getTripsByUserId" and "getVacationsByUserId" which are only simple SELECT query to database with a where clause.

Related

php - get values from array alphabetically as list group

I am trying to get values from MySQL array as alphabetically, and I want results like:
[B] => Array (
[id] => 6
[firstname] => Bon
[lastname] => Jone
),
Array (
[id] => 7
[firstname] => bon
[lastname] => doe
)
[H] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[J] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
Here is the code of what I have tried.
edited
$result = mysqli_query($GLOBALS['conx'],"SELECT * FROM $users_table ORDER BY firstname ASC");
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$row['alphabets'] = ucfirst($firstname[0]);
$data[] = $row;
}
But it outputs like this:
[0] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
[1] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[2] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[3] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
How can I get output like this:
A
Adam Smith
Alan smith
B
Bone Doe
Bone Joe
J
John Smith
.... etc
ucfirst returns the entire string with the first letter capitalised, you'll need to grab just the first letter with substr first.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$key = strtoupper($firstname[0]))
$data[$key][] = $row;
}
To get the output (roughly) like you want, try something like:
foreach ($data as $letter => $rows)
{
echo "<h1>{$letter}</h1>", PHP_EOL;
foreach ($rows as $row)
{
echo "<p>{$row['firstname']} {$row['lastname']}</p>", PHP_EOL;
}
}
Your attempt will not do what you want. To achieve this, you will have to create a nested array, then on each iteration check the first letter of the firstname. Check if that letter already exists as a key in the array, and create an item in your array with an empty array as its value, it if it doesn't, and then add the row data to it to that newly created empty array.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$firstLetter = strtoupper($row["firstname"][0]); // convert to upper case so all are the same
if (array_key_exists($firstLetter, $data) === false) $data[$firstLetter] = [];
// now just add the row data:
$data[$firstLetter][] = $row;
}
First use Order in your MySQL Query: ... ORDER BY firstname ASC
Create Arrays for Alphabets using PHP:
$Alphabetic_Array = array();
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['firstname'][0]][] = $row;
}
First of all, I suggest you to sort records in your query, otherwise you have to sort resulting array before grouping it:
SELECT * from tablename
ORDER BY firstname ASC, lastname ASC
Then, you can use array_map to group your array:
$result = array();
array_map
(
function( $row ) use( &$result )
{
$result[strtoupper(substr($row['firstname'],0,1))][] = $row;
},
$data
);
(Note that we have to call $result by reference)
Now the $result is an array like this:
Array
(
[B] => Array
(
[0] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[1] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
)
[H] => Array
(
[0] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
)
[J] => Array
(
[0] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
)
)
If you want/can use PDO instead of mysqli_, you can obtain desired result directly from MySQL query. Set your query in this way:
SELECT UPPER(SUBSTR(firstname,1,1)) as initial, tablename.* from tablename
ORDER BY firstname ASC, lastname ASC
and then, fetching in in this way:
$data->fetchAll( PDO::FETCH_ASSOC|PDO::FETCH_GROUP );
your $data will contain desired array, without need of additional processing.
The PDO::FETCH_GROUP option groups fetched results by first column returned by query, in your case the capitalized firstname first letter.
What about letting MYSQL do the logic?
SELECT * FROM users_table, SUBSTRING(firstName, 1, 1) as initial ORDER BY firstname ASC
Then you just can append each line to an array
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['initial'] = $row;
}
It's just pseudo code but I think the idea is pretty clear

PHP get value of one column in array

I'm writing some data off my MySQL database into an array using columns with php like this:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row->id = $row["ID"];
$row->product = $row["product"];
$row->aantal = $row["Aantal"];
$row->price = $row["Price"];
$od[] = $row;
}
} else {
echo "0 results";
}
now later I have to use the $row->id and $row->product of the different columns seperatly to get some more data out of another table in MySQL. I've been trying to accomplish this:
$to = 0;
foreach($od as $odt)
{
$odb= $odt[$to]["ID"];
$sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
$to++;
But this doesn't seem to work, I've tried dozen of others but can't seem to get this thing right...
Any solutions or remarks?
EDIT:
Array ( [0] => Array ( [ID] => 3 [product] => 10 [Aantal] => 1 [Price] => 3 ) [1] => Array ( [ID] => 4 [product] => 13 [Aantal] => 1 [Price] => 3 ) [2] => Array ( [ID] => 5 [product] => 3 [Aantal] => 3 [Price] => 4 ) )
You are doing it wrong, you are saving object in an array and trying the get the data with array, it should be as
foreach($od as $key=>$odt)
{
$odb= $odt->id;
$sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
}

Two Array's Trying to Combine where A Value is equal to a key?

I Have Two Array's One That is a 'App' Array and one is a 'Table' Array. Each Row in 'Table' has an 'AppID' As Shown Below. How can I combine the array to where the App_ID in the Tables Array is under the Same App_ID on the App Array? What I Currently Have is First and Want I Want is after that. I am using PHP. Thank Your for all of the Help!
App Array:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Project Manager
[App_Created] => 2014-12-17 16:31:57
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
Tables Array:
Array
(
[1] => Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
)
[2] => Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
I Want to Go to:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Kennedy_Fabricating_Project_Manager
[App_Created] => 2014-12-17 16:31:57
[Tables] = > Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
),
Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
My Current PHP Code:
//Get App List
$apps_sql = $conn->query("SELECT * FROM `Apps`") or die("Conn Query Apps Failed");
$apps = array();
while($apps = $apps_sql->fetch_array(MYSQLI_ASSOC)) {
$app_id = $apps['App_ID'];
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE `App_ID` = $app_id") or die("Conn Query Tables in Apps Failed");
// My Guess is Something Here?
$apps_a[$app_id] = $apps;
}
// Table List
$table_sql = $conn->query("SELECT * FROM `Tables`") or die("Conn Query Tables Failed");
$tables = array();
while($tables = $table_sql->fetch_array(MYSQLI_ASSOC)) {
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
}
It looks cleaner, and faster as you make only 2 queries instead of zillions
$apps_sql = $conn->query("SELECT * FROM `Apps`");
$apps_ids = array();
while ($app = $apps_sql->fetch_array(MYSQLI_ASSOC))
{
$apps_ids[] = $app['App_ID'];
$apps[$app['App_ID']] = $app;
}
$apps_ids = implode(',', $apps_ids);
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE IN ({$apps_ids})");
while($table = $table_sql->fetch_array(MYSQLI_ASSOC))
{
$apps[$table['App_ID']]['tables'][] = $table;
}
just change:
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
into:
$apps_a[$tables['App_ID']]['Tables'][$tables['Table_ID']] = $tables;

How to add new key-value to existing array in PHP

I have a form in PHP that takes in two values: server_id and user_id (which can be more than one separated by ','). I retrieve some data from a table and stored them as array. Using the same server_id and user_id, I would like to retrieve additional from another table but store them into the same array.
This is what I have so far.
//Data from PHP form stored in array
$inputData = Array ( [server_id] => 10
[user_id] => Array ( [0] => 111[1] => 222) )
//Existing array storing data retrieved from persons table
$userData =
Array
(
[0] => Array
(
[user_id] => 111
[server_id] => 10
[user_name] => Harry Pottter
[user_age] => 18 )
[1] => Array
(
[user_id] => 222
[server_id] => 10
[user_name] => Hermione
[user_age] => 18 )
)
//retrieving additional data from user_contact table
$sql = "SELECT user_phone, user_address FROM user_contact
WHERE user_id = ? AND server_id = ?";
foreach($user_id as $user)
{
$statement= $DB->link->prepare($sql);
$statement->bind_param("si", $server_id, $user);
$statement->execute();
if($resultSet = $statement->get_result())
{
while($row = $resultSet->fetch_assoc())
{
userData[$key]['user_phone'] = $row['user_phone'];
userData[$key]['user_address'] = $row['user_address'];
}
}
}
try using array_push()
like
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

compare in array with specific condition value

I am getting array after loping
while($num_rows1 = mysql_fetch_array($data_query_details1))
Now I want to check if my specific user_id ( suppose here user_id=3) stay 2/3 ( my specific value) times same date in array then print ok otherwise print need more.
Array
(
[0] => 3
[user_id] => 3
[1] => 2014-07-18
[date(FROM_UNIXTIME(date))] => 2014-07-18
)
Array
(
[0] => 3
[user_id] => 3
[1] => 2014-07-18
[date(FROM_UNIXTIME(date))] => 2014-07-18
)
Array
(
[0] => 4
[user_id] => 4
[1] => 2014-07-18
[date(FROM_UNIXTIME(date))] => 2014-07-18
)
any logic ?
$dates = array();
$stay = false;
$userid_to_check = 3;
while($row = mysql_fetch_array($data_query_details1)){
if($row['user_id']==$userid_to_check){
if(in_array($row[1], $dates)){
$stay = true;
break;
}
$dates[] = $row[1];
}
}
if($stay)echo 'ok';
else echo 'need more';
It's better to go with a more direct database select like the answers above though.
For example, what codebird mentioned:
$query = "select count(*) from your_table GROUP BY user_id HAVING date(FROM_UNIXTIME(date))='2014-07-18'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count>=2)echo 'ok';
else echo 'need more';
This should solve your issue:
SELECT user_id, COUNT(*) FROM your_table
WHERE DATE(FROM_UNIXTIME(date))='2014-07-18'
GROUP BY user_id

Categories