rewind one step back in mysql_fetch_array() - php

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/>';
}

Related

Array for a SQL database using PHP

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;
}

php mysql_fetch_array() not working as expected

$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}

PHP to display all MySQL columns without knowing how many there are

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.

Obtaining data from query in multidimensional array

I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks
Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}
You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`

mysqli_fetch_array while loop columns [duplicate]

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)) {

Categories