Echo Specific Data from an Associative Array? - php

This is for a recipe project where users use a form and enter their own recipes. I have that whole part working. Now I'm trying to retrieve the recipe's information from the database and display it on a page. Anyway, this is the code I have right now.
<?php
include_once('includes/connection.php');
include_once('includes/recipe.php');
$recipe = new Recipe;
if (isset($_GET['id'])) {
$id = $_GET['id'];
$basic_data = $recipe->fetch_data($id);
$sql1 = $pdo->prepare("SELECT recipes.*, categories.* FROM recipes
INNER JOIN categories
ON (recipes.category_ID = categories.category_ID)
WHERE recipes.recipe_id = ?");
$sql1->bindValue(1, $id);
$sql1->execute();
$results1 = $sql1->execute();
echo $results1 = $sql1->fetchAll(PDO::FETCH_ASSOC);
var_dump($results1);
?>
This is what I see on my webpage when this code runs. I've never worked with associative arrays before, so I'm really lost as to how I can echo specific data contained in one. For the purpose of this question, I'm focusing on the "category_name" and I'm trying to echo just the value stored in the "category_name" for this recipe, which happens to be "none". How do I echo just the word "none" to the page?
Arrayarray(1) {
[0]=> array(15) {
["recipe_ID"]=> string(1) "1"
["recipe_name"]=> string(20) "English Muffin Pizza"
["category_ID"]=> string(1) "1"
["servings_ID"]=> string(2) "13"
["prep_hours"]=> string(1) "0"
["prep_minutes"]=> string(2) "20"
["cook_hours"]=> string(1) "0"
["cook_minutes"]=> string(2) "10"
["oven_temp"]=> string(3) "350"
["directions"]=> string(402) "These are the directions."
["extra_comments"]=> string(37) "This is a short extra comment."
["recipe_favorite"]=> string(1) "1"
["recipe_photo"]=> string(0) ""
["created"]=> string(19) "2014-09-20 10:22:39"
["category_name"]=> string(4) "none" }
}
Please let me know if I can give you any more information. It's been a long day and I may be missing something that could help you to help me.

If you are strictly trying to echo category_name in this array you would just write:
echo $results1[0]['category_name'];

You need to use a loop to go through $results. That will echo category_name for all recipes.
foreach ($results1 as $recipe) {
echo $recipe['category_name'];
}
If you know you want the recipe at key 0 (first recipe), you can simply do:
echo $results[0]['category_name'];

Related

global $wpdb displaying garbage data along with results of my select query

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

PHP Mysqli fetch_assoc() on joined queries

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.

Apply foreach to multiple arrays?

I've been playing around with this one for a few days, I'm not a professional coder but I'm trying to put a nice basic system in place to manage checkin/out at a local volunteer rescue organization.
Basically I'm trying to get all members member with the ISLOGGEDIN value set as 1
$loggedin = mysql_query("SELECT * FROM members WHERE ISLOGGEDIN=1");
$loggedinarray=mysql_fetch_array($loggedin);
And present their information (name, etc) into a table:
foreach($loggedinarray as $key=>$value) {
echo "
<tr>
<td>".$value[firstname]." ".$value[lastname]."</td>
<td>".$value[timeloggedin]."</td>
</tr>
";
}
However the results I'm getting are quite random and not what I'm looking for, at all!
var_dump($loggedinarray) output:
array(12) { [0]=> string(5) "5395" ["SES_ID"]=> string(5) "5395" [1]=> string(7) "Anthony" ["FIRST"]=> string(7) "Anthony" [2]=> string(8) "LastName" ["LAST"]=> string(8) "Willison" [3]=> string(1) "1" ["ISLOGGEDIN"]=> string(1) "1" [4]=> string(1) "0" ["TRAINER"]=> string(1) "0" [5]=> string(1) "1" ["OFFICER"]=> string(1) "1" }
Any help would be greatly appreciated!
You have to use while; it was random, because it fetched only one row from table.
$loggedin = mysql_query("SELECT * FROM members WHERE ISLOGGEDIN = 1");
if (mysql_num_rows($loggedin) > 0) {
echo "<table>";
while ($row = mysql_fetch_array($loggedin)) {
echo "
<tr>
<td>".$row['FIRST']." ".$row['LAST']."</td>
<td>".$row['timeloggedin']."</td>
</tr>
";
}
echo "</table>";
}
This code will output every row from table, where ISLOGGEDIN = 1.
PS: about data $row['timeloggedin'], you dont have it in your query (as seen in var_dump), so it will be an empty string.

Grab ID from form array

I believe this is probably a very simple question, but since I'm just dealing with numbers, it sorta makes my brain hurt.
Below is my form with some lines removed due to being irrelevant to the question
$envList = $link->query("SELECT * FROM environments");
echo "<form action = 'editEnvOrderExec.php' method = 'post'>";
echo "<input type = 'hidden' name = 'userID' value = '".$userID."'>"
while($row = $envList->fetch_assoc()){
$eName = $row['name'];
$dID = $row['displayID'];
$eID = $row['id'];
echo $eName.": <input type = 'text' name = 'eID[".$eID."]' value = '".$dID."'><BR>";
}
Upon submitting the $_POST looks like this
array(2) {
["userID"]=>
string(1) "2"
["eID"]=>
array(6) {
[1]=>
string(1) "1"
[3]=>
string(1) "2"
[4]=>
string(1) "3"
[5]=>
string(1) "4"
[6]=>
string(1) "5"
[8]=>
string(1) "6"
}
}
I need to take the values in the brackets, [1][3][4][5][6][8] and for each one have a mysql statement update the displayID with the value [1][2][3][4][5][6]. My problem is I can't figure out how to target each one...
NOTE: I know I need to sanitize values, as well as check if a display ID is already used and such, but this is just v0.1. Trying to get functionality down, then I can tackle those other issues
Easiest way is if you're iterating over the loop using foreach:
$eID = $row['eID'];
foreach ($eID as $key => $value) {
// here $key is the array key you're looking for.
}

The result from mysql_fetch_assoc() compounds old values onto new values. Any ideas?

I'll start with the problem. I'm looping through mysql_fetch_assoc() calls to display all fields from a row. Every new pass gives me the new row PLUS the old row values as well. It compounds each pass. I've tried many things and looked through many posts and forums and haven't quite found what I need to fix it. Any help is appreciated.
edit: Sorry but the indentation gets messed up after I post the question.
Here's the MySQL table script:
CREATE TABLE pay_hours
(
_key int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
_userNumber int(11),
_hoursWorked double
);
CREATE TABLE pay_dates
(
_key int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
_userNumber int(11),
_dateWorked date
);
Here's the query:
$query = "SELECT h._userNumber, d._dateWorked, h._hoursWorked FROM pay_hours h, pay_dates d WHERE d._userNumber=h._userNumber ORDER BY d._dateWorked DESC"; // gets the user, hours and dates and displys most recent dates first.
$result = $keyFrameObject->Execute($query); // wrapper for mysql_query()
Here's the loop:
$row = mysql_fetch_assoc($result);
while ($row)
{
$table .= "<tr>";
foreach ($row as $field)
{
$table .= "<td>" . $field . "</td>";
}
$table .= "</tr>";
$row = mysql_fetch_assoc($result);
}
It's a PHP page and I will eventually echo a table created with this data. I'm entering values for dateWorked and hoursWorked while using the same userNumber value for testing purposes. Here's some sample input and output (using var_dump($row) ):
input:
date = 2011-08-05
hours = 1
output:
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" }
Now the page has posted back and I'll enter in a new set of values:
input:
date = 2011-08-04
hours = 5
output (unformatted):
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "5" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "1" } array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "5" }
output (formatted):
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "5" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-05" ["_hoursWorked"]=> string(1) "1" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "1" }
array(3) { ["_userNumber"]=> string(3) "333" ["_dateWorked"]=> string(10) "2011-08-04" ["_hoursWorked"]=> string(1) "5" }
Every time I enter in values and run through the code, it compounds further. I believe the issue is the loop but I'm not sure. Somehow $row is maintaining value after a post back.
Thanks again for the help and let me know if any more info is needed.
Change $table .= ""; to $table = "";
The .= is preserving the values of $table from the previous loops.
Problem solved. The answer is in the comments below. Thanks for the help.
I've figured it out. Because of the design of the tables, it would insert twice which would cause compounding. I changed everything into a single table and the ambiguity disappeared. Thanks for all of your help. I'm not sure how to mark this as solved, but if the mods are watching, could you help a brother out? – Matt 9 hours ago

Categories