Formatting $wpdb->get_results - php

I used
...
$result = $wpdb->get_results( $query );
foreach ( $result as $print ) {
echo $print->name;
echo $print->count;
echo "<br>";
}
output is:
jo2
clea10
jim10
Now I somehow need to make it like
['jo', '2'],
['clea', '10'],
['jim', '10'],
I tried
<?php
foreach ( $result as $print ) {
echo "['".$print->name."', '".$print->count."'],";
}
?>
And
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "['".$row['name']."', ".$row['count']."],";
}
}
But it does not work. I'm trying to run this inside Wordpress using wordpressDatabase that is why I used $wpdb->get_results

I am not sure what you were querying so I mocked up another example to just return the pages of the site. You can substitute post_name for name and count for ID in your example.
I just added spaces to your attempt to match WP Standards a little closer but working with quotations is never that readable.
$result = $wpdb->get_results ( "
SELECT *
FROM $wpdb->posts
WHERE post_type = 'page'
" );
foreach ( $result as $key => $print ) {
echo "['" . $print->post_name . "', '" . $print->ID . "'],<br>";
}
Another approach, if you are comfortable reading it this way, is to use double quotes around the entire output.
foreach ( $result as $key => $print ) {
echo "['{$print->post_name}', '{$print->ID}'],<br>";
}
If neither approach is working I'd suggest you may have an issue with your query in general but it is hard to say without more inforamtion

Related

Add multiple SQLresults to an array while in a foreach loop

I am having some trouble trying to get this done. The issue is:
I have an array that looks like
wants_arr_flat ( [0] => booze [1] => nudes [2]
=> rooms
I want my foreach loop to go through these values making a different SQL statement and then saving the result of that SQL statement on to another array. The code I am trying to work with now is this.
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
$want_match_arr = mysqli_fetch_row($result);
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo
Obviously this is just overwriting the last array each iteration so I only end up with one result in the array.
instead of
$want_match_arr = mysqli_fetch_row($result);
use
$want_match_arr[] = mysqli_fetch_row($result);
If you get multiple rows from SQL then this is better.
$want_match_arr = [];
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
while ($row = mysql_fetch_assoc($result)) {
$want_match_arr[] = $row;
}
}
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo

add values with PHP

I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.
So far I've been able to display both entries for value by using the following.
function showTotal() {
global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Query FAILED' . mysqli_error());
} else if (isset($failed)) {
echo "Failed";
}
while ($row = mysqli_fetch_assoc($result)) {
$value = $row['value'];
echo "$value";
}
}
What I really want is these values added together rather than displaying alongside each other.
Thanks
James
I haven't tested it, but something like this could potentially be a one-liner.
echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );
That said, if you do not need all the results, this is a better option:
$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];
Using php you could sum up the values like so:
$value = 0;
while ($row = mysqli_fetch_assoc($result)) {
$value += $row['value'];
}
echo $value;
While I personally would opt to go with the solution offered by #jm, PHP does offer another way with its array_sum(), as follows:
<?php
$value = 0;
while ($row[] = mysqli_fetch_assoc($result)) {}
echo array_sum($row['value']);
See Manual
Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.

Creating html list from php array

I am trying to create a html list from a php array that I've fetched from a SQL query, but no matter what I just get really weird results.
$dbf = mysql_query("SELECT * FROM testdb") or die(mysql_error());
$info= mysql_fetch_array($dbf);
foreach($info as $x)
{
echo '<li>' . $x['name'] . '</li>';
}
Instead of getting the names in my database I get the following values
a
a
d
n
k
I am probably doing something wrong?
In your code, you are performing mysql_fetch_array($dbf) function only once. This only selects the first row from your result set. What you need to do is send this function as a condition on a while loop. Consider the following alterations on your code:
$dbf = mysql_query("SELECT * FROM testdb") or die(mysql_error());
echo '<ul>';
while( $info = mysql_fetch_array( $dbf, MYSQL_ASSOC ) )
{
echo '<li>' . $info[ 'name' ] . '</li>';
}
echo '</ul>';
In the above code, your while loop iterates through each and every tuple that your SELECT query produces. That should solve your problem.
The problem is mysql_fetch_array() only fetches the first row from the result set.
You need to execute mysql_fetch_array in a loop.
while($info= mysql_fetch_array($dbf))
{
echo '<li>' . $info['name'] . '</li>';
}

calling PHP multi dimensional arrays outside of foreach loop

I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];

Combine array elements into single string

So this is what I'm trying to do..
$sql="SELECT * FROM `members";
while($rew = mysql_fetch_array($sql)){
$var[] =",'".$rew['username']."'";
}
print_r ($var)
So I get the result:
Array ( [0] => ",'John'", [1] => ",'Mason'", [2] => ",'Greg'", [3] => ",'Paul'" )
So now I want the variable to display all results when I echo. For example:
<?php echo $var[1] ?>
And the result will be just ,'Mason'.
How do I get it so that I can echo $var[*] and get all the results. "John,Mason,Greg,Paul".
I have been trying to figure this out for a very long time and is getting very frustrating for me. Can someone please help me.
Use PHP's implode function.
<?php echo implode(",", $var) ?>
And change your loop code to:
$var[] = $rew['username'];
You can't use echo on an array directly. You could either loop through the array using a control structure like for or foreach, or you can use a built-in function that is designed to operate on arrays. To get the output you are looking for try:
<?php echo implode(',', $var);?>
Here's a good tutorial: Tizag - MySQL Fetch Array
This should work:
$query = "SELECT * FROM `members`";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['username'];
echo "<br />";
}
You can change your loop to something like:
$var = "";
while($rew = mysql_fetch_array($sql)){
$var .= ",'" . $rew['username'] . "'";
}
Here is a simple one liner that also adds the quotes
<?php echo "'" . implode("','", $var) . "'"; ?>
and if you use pdo, you can get the usernames even easier
<?php
$usernames = $db->query("SELECT username FROM members")->fetchAll(PDO::FETCH_COLUMN);
echo "'" . implode("','", $usernames) . "'";
?>

Categories