entries and images and have been trying every way I can find to join them to get the below result
entries:
entry_id
name
images:
entry_id
image_url
I'm using php and would like to be able to retrieve all associated image_url rows for a given entry_id and combine them with the other information from the entries table.
So I have something like:
entries:
1, Brian
2, Steve
3, Jane
images:
1, images/brian1.jpg
1, images/brian2.jpg
2, images/steve.jpg
3, images/jane_1.jpg
3, images/jane_2.jpg
3, images/jane_3.jpg
And would like to get an array back something like
array(3) {
[0]=>
array(3) {
["entry_id"]=>
string(1) "1"
["name"]=>
string(5) "Brian"
["images"]=>
array(2) {
["image_url"]=>
string(17) "images/brian1.jpg"
["image_url"]=>
string(17) "images/brian2.jpg"
}
}
[1]=>
array(3) {
["entry_id"]=>
string(1) "2"
["name"]=>
string(5) "Steve"
["images"]=>
array(1) {
["image_url"]=>
string(16) "images/steve.jpg"
}
}
[2]=>
array(3) {
["entry_id"]=>
string(1) "3"
["name"]=>
string(5) "Jane"
["images"]=>
array(3) {
["image_url"]=>
string(18) "images/jane_1.jpg"
["image_url"]=>
string(18) "images/jane_2.jpg"
["image_url"]=>
string(18) "images/jane_3.jpg"
}
}
}
Thank you!
Having tested none of this, I assume you want something like this:
SELECT * FROM entries INNER JOIN images ON images.entry_id = entries.entry_id
Then loop through those results:
$entries = array();
while ($row = mysql_fetch_assoc($data))
{
if (!isset($entries[$row['entry_id']]))
{
$row['images'] = array();
$entries[$row['entry_id']] = $row;
}
$entries[$row['entry_id']]['images'][] = $row['image_url'];
}
Then you can loop through this return:
foreach ($entries as $entry)
{
foreach ($entry['images'] as $image);
// do something interesting
}
That should about do it for you, but you may have to modify some things.
Do you have your database connection code sorted?
I believe your looking for a full outer join. Check this resource for SQL examples for the different joins.
http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
The easy way is something like this
select * from entries, images where images.entry_id = entries.entry_id group by entries.entry_y;
making the join is something like this:
SELECT * FROM entries INNER JOIN images ON images.entry_id = entries.entry_id
For display array like that, you cannot use join, try this :
select all data in table entries
foreach table entries, when foreach include table images
Ex:
$q_e = "SELECT * FROM entries";
$result_entry = mysql_query($q_e);
$entries = array();
$images = array();
while($entry = mysql_fetch_array($result_entry)) {
$q_i = "SELECT * FROM `images` WHERE `entry_id` = '".$entry['entry_id']."'";
$result_image = mysql_query($q_i);
while($image = mysql_fetch_array($result_image)) {
$images[] = array(
'image_url' => $image['image_url']
);
}
$entries[] = array (
'entry_id' => $entry['entry_id'],
'name' => $entry['name'],
'images' => $images,
);
}
echo 'pre>';var_dump($entries);
Related
First of all, I couldn't think of any better title, sorry if you find it inapropiate.
I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.
The first database accounting has
subscriber_id | amount | zone_id
stored in the table named cdr
The second db billing has stored inside the table billing_zones these values:
zone_id | zone_name
Everything I've done works fine, but the resulting array is not what I expected/wanted.
This is my code:
try {
$conn = new PDO('mysql:host=host;dbname=accounting','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
FROM `billing`.billing_zones a INNER JOIN cdr b
ON a.`id` = b.`source_customer_billing_zone_id`
WHERE destination_account_id = :destinationId
GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));
foreach ($stmt as $row) {
$data[] = $row;
}
for ($i=0; $i < sizeof($data); $i++) {
$sanitizedData[$i] = array(
0 => $data[$i][0],
1 => $data[$i][1],
2 => $data[$i][2]
);
}
/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
$newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
}
}
var_dump($sanitizedData);
The result of the code above my ATTEMPT comment is a big array, I will show you a piece of it so you can understand better what I want to do:
[1047]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "V30048086"
[2]=>
string(10) "460.440000"
}
[1048]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 902 Nivel 1"
[1]=>
string(9) "V30048086"
[2]=>
string(9) "87.301236"
}
[1049]=>
array(3) {
[0]=>
string(25) "Llamadas Fijos nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "64.340367"
}
[1050]=>
array(3) {
[0]=>
string(27) "Llamadas Moviles nacionales"
[1]=>
string(9) "W24154073"
[2]=>
string(10) "116.480000"
}
[1051]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "W24154073"
[2]=>
string(9) "62.559759"
}
To clarify:
array[n][0] is the aforementioned zone_name
array[n][1] is the subscriber_id - The id defining the customer
array[n][2] is the SUM() of the amount for that id in that zone.
So the result is that for every id, there are several arrays for each zone.
What I want to do is to group those in a unique array like:
[1051]=>
array(3) {
[0]=>
string(9) "W24154073"
[1]=>
string(28) "Llamadas Premium 901 Nivel 1"
[2]=>
string(9) "62.559759"
[3]=>
string(28) "Llamadas Moviles nacionales"
[4]=>
string(9) "116.480000"
[5]=>
string(28) "Llamadas Fijos nacionales"
[6]=>
string(9) "64.340367"
.
.
.
If there were more
}
As #Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:
["W24154073"]=>
array(3) {
[0]=>
string(28) "Llamadas Premium 901 Nivel 1"
[1]=>
string(9) "62.559759"
[2]=>
string(28) "Llamadas Moviles nacionales"
[3]=>
string(9) "116.480000"
[4]=>
string(28) "Llamadas Fijos nacionales"
[5]=>
string(9) "64.340367"
.
.
.
If there were more
}
This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.
I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.
If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.
Thank you for the help, have a great weekend!
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.
This can be a achieved in quite a simple fashion, like this:
$data = [];
foreach ($stmt as $row) {
// $row[1] is the subscriber_id
$data[$row[1]][] = $row[0]; // $row[0] is zone_name
$data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);
The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.
I have a custom table in MySQL database, which I am trying to query using global $wpdb. I have defined my query using information available from the following two sources:
https://codex.wordpress.org/Class_Reference/wpdb
https://wordpress.stackexchange.com/questions/233021/display-data-on-word-press-site-posts-and-pages-from-mysql-table
This is how the data is in phpMyAdmin:
The query seems to be working fine as it selects data from my custom table, however the output seems to contain garbage/unnecessary information apart from the information that is available in the table.
I want it to display as a table/similar to how it is displayed in phpMyAdmin, where I am able to associate the SrNo, Compound etc with other columns in the table:
add_shortcode('wpse_233031_shortcode', function(){
global $wpdb;
$myrows = $wpdb->get_results( "SELECT `SrNo`, `Compound` FROM PNaphtha");
//$results = $wpdb->get_results( "SELECT `SrNo`, `Compound` FROM PNaphtha" );
ob_start();
echo var_dump($myrows );
//return ob_get_clean();
});
I get the following results
array(10) {
[0]=> object(stdClass)#6275 (2) {
["SrNo"]=> string(1) "2"
["Compound"]=> string(12) "abietic acid"
}
[1]=> object(stdClass)#6274 (2) {
["SrNo"]=> string(1) "3"
["Compound"]=> string(12) "acenaphthene"
}
[2]=> object(stdClass)#6273 (2) {
["SrNo"]=> string(1) "4"
["Compound"]=> string(6) "acetal"
}
[3]=> object(stdClass)#6272 (2) {
["SrNo"]=> string(1) "5"
["Compound"]=> string(12) "acetaldehyde"
}
[4]=> object(stdClass)#6271 (2) {
["SrNo"]=> string(1) "6"
["Compound"]=> string(9) "acetamide"
}
[5]=> object(stdClass)#6270 (2) {
["SrNo"]=> string(1) "7"
["Compound"]=> string(11) "acetanilide"
}
[6]=> object(stdClass)#6269 (2) {
["SrNo"]=> string(1) "8"
["Compound"]=> string(11) "acetic acid"
}
[7]=> object(stdClass)#6268 (2) {
["SrNo"]=> string(1) "9"
["Compound"]=> string(16) "acetic anhydride"
}
[8]=> object(stdClass)#6267 (2) {
["SrNo"]=> string(2) "10"
["Compound"]=> string(7) "acetone"
}
[9]=> object(stdClass)#6266 (2) {
["SrNo"]=> string(2) "11"
["Compound"]=> string(19) "acetone cyanohydrin"
}
}
Although, all of the information I queried is available here, there is also a lot of unnecessary information.
I tried the following changes, however none of them seems to be working
$myrows = $wpdb->get_row( "SELECT `SrNo`, `Compound` FROM PNaphtha"); // get_row
output_type changed to ARRAY_A, ARRAY_N, OBJECT_K
echo var_dump changed to echo array
I will appreciate if you could please advise on how to get the results to format as a table or array. Also, I have placed the above code in the functions.php file of my theme. Is there a better way to do this?
So, you're getting object as output, that's why you're seeing that information in there. Make the following change. Add 'ARRAY_A' (associative array) to the end of your function call.
$wpdb->get_results( "SELECT `SrNo`, `Compound` FROM PNaphtha", ARRAY_A);
That will keep your query from being returned as an object and your var_dump will look the way you expect.
It may be because you are using var_dump
The var_dump function displays structured information about variables/expressions including its type and value.
I would recommend using print_r
The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements.
You should be able to see a change if you change
var_dump($myrows )
to
print_r($myrows)
Here's how I did what you are wanting (Without echoing the result):
$sql = "SELECT `Srno`,`compound` FROM `pnaphtha`";
$result = $conn->query($sql);
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row['Srno']."</td><td>".$row['compound']."</td></tr>";
}
echo "</table>";
However since you are using WordPress I would suspect it would be something along the lines of
global $wpdb;
$sql = "SELECT `SrNo`, `Compound` FROM PNaphtha";
//you may need to add ARRAY_A
$myrows = $wpdb->get_results($sql);
echo "<table>";
while($myrows = $result->fetch_assoc()) {
echo "<tr><td>".$myrows['SrNo']."</td><td>".$myrows['Compound']."</td></tr>";
}
echo "</table>";
I can't actually test the wordpress version as I can't be bothered to set up a wordpress install haha
I am trying to provide a count of certain sizes of lockers. My SQL statement is:
$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";
a var_dump in a loop of the rows gives me the following (many more rows are possible):
array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) }
I want to obtain a JSON string that looks like this:
{
"SizeList": {
"15x30x45": 6
"45x30x45": 4
}
}
I have tried a lot of different methods (including converting it into an object, but I can't get the value of the size as an index. For example, I get different variations of:
[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}"
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"
Any help appreciated...
You could just manually create the object like this:
$sizeList = new stdClass();
foreach ($results as $row) {
$sizeList->{$row['Locker']} = $row['count(*)'];
}
echo json_encode(array('SizeList' => $sizeList));
Whenever I run this piece of code I get only the values from test2 due to the columns being the same.
$Return = array();
$Output = $MySQLi->query("SELECT * FROM test1 as A LEFT JOIN test2 as B ON A.abc=B.abc");
while($Row = $Output->fetch_assoc()) {
$Return[] = $Row;
}
var_dump($Return);
This is what I get.
array(1) { [0]=> array(2) { ["abc"]=> string(1) "2" [123]=> string(1) "3" } }
Is there a way to make fetch_assoc() return something like this?
array(1) { [0]=> array(2) { ["A.abc"]=> string(1) "7" [A.123]=> string(1) "8" ["B.abc"]=> string(1) "2" [B.123]=> string(1) "3" } }
You need to use alias while selecting the data and best is select only which is needed instead of using *
Write your query as below:-
SELECT A.abc as 'A.abc',A.123 as 'A.123',B.abc as 'B.abc',B.123 as 'B.123'
FROM test1 as A
LEFT JOIN test2 as B
ON A.abc=B.abc
Although in general the answer to this question is to define aliases in your query, to solve this particular inconvenience (along with infinite number of real problems), you have to make all the similar data into a single table. This is the only proper way.
Im trying to setup a dynamic settings database for my CMS
Database is set up with two columns.
Name | Value
Template | Exige
InstallFolder | v2
Basically I want to pull all the data out and put it into different variables.
for example i'm trying to set my base_folder(installation folder) into a variable.
So say $base_folder = $CoreSettings[1] output which should show (v2)
$sql = "SELECT * FROM core_settings";
$query = mysqli_query($dbc, $sql) or die (mysqli_error($dbc));
$CoreSettings = array();
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$CoreSettings[] = $row;
}
$base_folder = $CoreSettings;
foreach( $CoreSettings as $key => $val)
{ $$key = $val; }
var_dump($base_folder);
This then outputs:
array(5) { [0]=> array(2) { ["name"]=> string(8) "Template" ["value"]=> string(5) "exige" } [1]=> array(2) { ["name"]=> string(13) "InstallFolder" ["value"]=> string(2) "v2" } [2]=> array(2) { ["name"]=> string(16) "MaintainanceMode" ["value"]=> string(1) "0" } [3]=> array(2) { ["name"]=> string(4) "Logo" ["value"]=> string(8) "Logo.png" } [4]=> array(2) { ["name"]=> string(8) "SiteName" ["value"]=> string(18) "Black Nova Designs" } }
I would like to just get the InstallFolder Value.
so
$base_folder = V2
Sorry if this comes across stupid just really racked my brain about, and code is probably quite messed up due to trying multiple methods.
But in the long run I would like to get every setting out of the database and be able to assign a variable to each setting.
for example
$SiteName = $CoreSettings[4];
$maintenance = $CoreSettings[2];
Thanks In advanced.
Kyle
Index you $CoreSettings array with the values of the 1st column, then you can access the values by the appropriate key:
$CoreSettings = array();
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$CoreSettings[$row['name']] = $row['value'];
}
echo $CoreSettings['InstallFolder']; //outputs V2
echo $CoreSettings['Template']; //outputs Exige