This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 months ago.
Should be pretty basic, but I can't get it to work. I have this code to iterate over a mysqli query:
while($row = mysqli_fetch_array($result)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
It works and returns:
Variable #1: (Array, 3 elements) ↵
0 (String): "4testtest" (9 characters)
1 (String): "1Hello world!Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!" (99 characters)
2 (String): "2Sample PageThis is an example page. It's different from a blog post because it will stay in one place and will show up in
your site navigation (in most themes)." (161 characters)
The problem is that it puts all three colums into one column, so I can't access them seperatly.
This for example:
0 (String): "4testtest" (9 characters)
Should be seperated into 4, test, test
When I do this:
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row['post_id'];
$posts['post_title'] = $row['post_title'];
$posts['type'] = $row['type'];
$posts['author'] = $row['author'];
}
It only outputs 1 row instead of all three …
Any help is greatly appreciated!
Get all the values from MySQL:
$post = array();
while($row = mysqli_fetch_array($result))
{
$posts[] = $row;
}
Then, to get each value:
<?php
foreach ($posts as $row)
{
foreach ($row as $element)
{
echo $element."<br>";
}
}
?>
To echo the values. Or get each element from the $post variable
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
-ID Title
-1 Gary
-2 John
-3 Michaels
Both will works perfectly in mysqli_fetch_array in while loops
while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
(OR)
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
mysqli_fetch_array() - has second argument $resulttype.
MYSQLI_ASSOC: Fetch associative array
MYSQLI_NUM: Fetch numeric array
MYSQLI_BOTH: Fetch both associative and numeric array.
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
Try this...
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
Related
Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}
This question already has answers here:
SQL, How to Concatenate results?
(7 answers)
Closed 7 years ago.
I am trying to do something that I thought would be very simple but it's driving me crazy.
I have the following data:
ID --- Name
1 --- Joe
2 --- Bob
3 --- Jim
4 --- Mike
I want to be able to show the results of this from MYSQL as:
"Joe", "Bob", "Jim", "Mike"
I tried CONCATENATE tutorials, but they all seem to be for merging like ID's.
$sql = "SELECT names, CONCAT_WS('', 'names') as namelist FROM peoplenames";
$result = $conn->query($sql);
echo $row["namelist"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$names = $row["nameslist"];
echo $names;
}
}
If I echo outside the loop I only get the most recent result.
Any ideas?
The problem is that you are overwriting the contents of $names each time round the loop.
Change your code like this
$sql = "SELECT names FROM peoplenames";
$result = $conn->query($sql);
$names = NULL;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$names .= sprintf('"%s",',$row['names']);
}
// output amalgamated date
rtrim($names, ',');
echo $names;
}
Change your query to SELECT names FROM peoplenames and use PHP concat for a string:
$names = "";
while($row = $result->fetch_assoc()) {
$names .= '"' . $row["names"] . '",';
}
echo $names;
Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);
this is the values in the $result
id name
1 a
2 b
2 c
2 d
3 e
..
I'm creating a loop function using mysql_fetch_array()
while($row = mysql_fetch_array($result)) {
$temp_id = $row['id'];
while($temp_id == $row['id']) {
if($temp_id == $row['id']) {
mysql_fetch_array($result);
}
$temp_id = $row['id'];
echo $row['name'].",";
}
echo "<br/>";
}
this works but the problem is, the mysql_fetch_array jumps on one of the values during the transition of the id's..
I want the values of this to be like these
a
b,c,d
e
my question is, is there a simple rewind function that will step only once in the rows?
I have searched about the mysql_data_seek() but I think this would require additional control variables like $i to locate the address..
thanks.. any suggestions and function samples will be very great!
Use one loop with mysql_fetch_array first to create an array of the rows. Then, iterate over the rows themselves.
Based on the update to your question it seems like you would want to use GROUP_CONCAT in the query, but you can still do it in PHP:
$rows = array();
while($row = mysql_fetch_assoc($result)) {
if (!isset($rows[$row['id']]) {
$rows[$row['id'] = array();
}
$rows[$row['id']][] = $row['name'];
}
foreach ($rows as $row) {
echo implode(',', $row) . "<br>";
}
Try this code
while($row = mysql_fetch_array($result)) {
$temp[$row['id']][] = $row['name'];
}
foreach($temp as $row) {
echo implode(',', $row) . '<br/>';
}
I have a mysql query:
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
echo '
<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'
';
}
This query will generally select between 2 and 5 different rows and display them in a list.
I want the first echoed line to only appear once and the second line should appear between 2 and 5 depending on the data in my db.
I am sure there is a simple way to do this, I've tried GROUP BY mag but this will eliminate the remaining 1-4 pieces of data I wish to display.
Not sure I understand your question, as the following solution seems too simple!
$row = mysql_fetch_array($result);
echo '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'';
while ($row = mysql_fetch_array($result)) {
echo ''.$row['title'].'';
}
May be this is a solution to your problem ?
$lines = '';
unset($hgroup);
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
if (!isset($hgroup)) {
$hgroup = '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>';
}
$lines += '
'.$row['title'].'
';
}
echo $hgroup.$lines;