Combine array elements into single string - php

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) . "'";
?>

Related

Formatting $wpdb->get_results

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

Store multiple rows from mysql database into one single variable

this is really hard for me, i'm trying to store multiple rows from my table in mysql into a single variable
$mysql_statementJc = "SELECT * FROM `dog`.`cat` WHERE `name` = '$name'";
$mysql_commandJc = mysql_query($mysql_statementJc);
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$groupConcat = $followI . " OR ";
echo $groupConcat;
}
This is my appproach, so at the end of it all i can get "sam, john, bob" saved as $groupConcat which can then be used elsewhere.
Many thanks.
you want to create a concatenated string, php has the .= syntax for this:
$groupConcat='';
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat .= $row['industry'] . " OR ";
}
echo $groupConcat; //no point echoing inside the loop
sometimes a better approach is to use an array and implode()
$groupConcat=array();
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat[] = $row['industry'];
}
echo implode(' OR ',$groupConcat);
Each time through the loop, add the desired value to an array. Then, after the loop, use the implode() function to create your desired output.
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$resultArray[] = $followI;
}
$groupConcat = implode(" OR ", $resultArray);
echo $groupConcat;
Note that you should really stop using the mysql library and instead use mysqli or PDO.
You can also do it as:
$followl = array();
while($row = mysql_fetch_array($mysql_commandJc))
{
$followl[] = $row['industry'];
}
$groupConcat = implode(" OR ",$followl);
echo $groupConcat;
Some Explanation:
Store values into an array $followl and than use implode() function for imploding with OR.
Side note:
Please use mysqli_* or PDO becuase mysql_* is deprecated and no more available in PHP 7.

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'];

online server wont show string values

i have this code, where i get an array and make it a string, on my localhost show the values correctly (1,2...) but on my online server shows (,,) no numbers, just the commas. Does someone know what this issue may be?
Heres my code
<?php
error_reporting(E_ALL);
CONECTION
$sql = "select id from table where id=1";
$result = mysql_query( $sql);
$myArray= array() ; //Here you must declare it as array
while($row = mysql_fetch_array($result)){
$popurl = $row['id '];
$myArray[] = $popurl;
}
$string = "" . implode(", ", $myArray) . "" ;
echo $string;
?>
Please need help
It's a simple typo problem:
$row['id '] is not defined. Correct it to $row['id'] and you should be fine.

How to make echo a PHP array

when I attempt to echo these names, nothing comes up...
//
$getuser = "SELECT * FROM user WHERE account_id = $id";
$showuser = #mysqli_query ($dbc, $getuser); // Run the query.
while ($row = mysqli_fetch_array($showuser, MYSQLI_ASSOC)) {
$names[]=$row['user_username'];
}
echo $names;
To Echo an Array use
print_r($names)
Echo will only print out a simple variable (Text, Number). print_r is used to format and print out complex types such as arrays and objects.
Further information can be found on the php.net website.
http://php.net/manual/en/function.print-r.php
You can use print_r() or var_dump()
Instead of echo use print_r.
print_r($names);
Like that.
you should initialize $names as array before the while loop $names = array();

Categories