Fetch all fields from all rows - MYSQL - php

I understand this could appear alarming but bear with me.
I need to echo every field in every row in a table.
This is only an example - I have removed the HTML wrapped around it to improve readability.
$a = 1;
while ($a <= $count_rows) {
$query = "SELECT col1, col2 etc.. FROM table WHERE `id`='$id'";
$result = mysqli_query($con, $query);
$i = 1;
while($i <= $count_fields) {
$row = mysqli_fetch_array($result, MYSQL_NUM);
echo "$row[$i]";
$i++;
}
$a++;
$id = $a;
}
This only outputs the first field of every row? Why?
If I echo $row[2] I get nothing!

If I echo $row[2] I get nothing!
because it's actually third item
and there is some strange code interfering with $i variable
Anyway, to get every column from every row ou need a code like this
$query = "SELECT * FROM table";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
foreach ($row as $index => $value) {
echo "$index => $value, ";
}
echo "<br>\n";
}

Related

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.

How to avoid last added 2 data in while loop

how to avoid last added 2 data in while loop
$counter = 0;
$data=mysql_query("select * from tbl_sub_product");
$cnt = sizeof(mysql_fetch_assoc($data));
while($row= mysql_fetch_assoc($data)) {
if(($counter==$cnt-1) || ($counter== $cnt-2)){
}
echo $id = $row['id'];
}
is this a correct way.?is there any other way.? please help me
Firstly, as #Twinfriends said you should avoid using mysql_ functions.
You need to actually increment your $counter. You can do this by $counter++ (which is basically shorthand for $counter = $counter + 1 or $counter += 1).
Also, as #jeroen pointed out, the way you're checking for the count would have
returned the first row of your results so it would be missing from your while loop.
Given you the column count rather than the row count.
With mysql_ functions you need to use mysql_num_rows() for this.
$counter = 0;
$data = mysql_query("select * from tbl_sub_product");
$cnt = mysql_num_rows($data);
$stop = $cnt - 2;
while ($row = mysql_fetch_assoc($data)) {
$counter++;
if ($counter >= $stop) {
break;
}
echo $id = $row['id'];
}
break; inside a loop with stop the loop there and then. If you have the situation where you want to skip an iteration but you don't want to stop the loop you can use continue; instead.
Hope this helps!
The solution would be simple. Adding an additional condition within your while loop is not required at all, consider the solution below and Moreover mysql_functions are deprecated so I will suggest you to go with mysqli_functions
$count = 1;
/* Here $db would be something like $db = mysqli_connect('YOUR_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'); */
$data = mysqli_query($db, "select * from tbl_sub_product");
$rows_count = mysqli_num_rows($data);
while($count++ < $rows_count-2 && $row = mysqli_fetch_array($data)) {
echo $id = $row['id']
}
That's all you have to do.
You can do it like this
$counter = 0;
$data=
mysql_query("select*
from tbl_sub_p roduct");
$cnt =mysql_num_rows($data);
$run=$cnt-2;
while($row=
mysql_fetch_assoc($data)) {
$count++;
if($count!=$run)
{echo $id = $row['id'];
}
}
If you want to avoid last two entries added in database then simply modify your query to:
$data = mysql_query("SELECT * FROM tbl_sub_product ORDER BY id DESC LIMIT 2,18446744073709551615");//it will start selecting from 3rd record and leave first two records in database which are actually last inserted records
this is the answer for my question
$counter = 0;
$data=mysql_query("select* from tbl_sub_product");
$cnt =mysql_num_rows($data);
$run=$cnt-0;
$run1=$cnt-1;
while($row= mysql_fetch_assoc($data)) {
$count++;
if($count!=$run && $count!=$run1)
{
echo $id = $row['id'];
}
}

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

I've some issues with an array $row fetched from MySQL

I've some issues with an array fetched from MySQL
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
mysql_fetch_row($result);
echo $row[0]; // doesn't work
echo $row[1]; // doesn't work
but this work
echo $row["FirstFieldName"] //OK
...
how should I change the following code to make it work?
for ( $i = 0; $i < count( $row ); $i++ )
{
echo $row[ $i ];
}
thanks
Do below changes. use mysql_fetch_array instead of mysql_fetch_row()
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row=mysql_fetch_array($result);
for ( $i = 0; $i < count( $row ); $i++ )
{
echo $row[ $i ];
}
Try using mysql_fetch_array() instead.
The three functions you should look into are:
mysql_fetch_row,
mysql_fetch_array, and
mysql_fetch_assoc
Each does things a little differently.
Try it this way:
$sql = "SELECT id,email FROM people WHERE id = '42'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row[0];
}
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row=mysql_fetch_array($result);
echo $row[0];
echo $row[1];
it will work
mysql_fetch_row returns one row, so to be able to use it you should do :
while( $row = mysql_fetch_row( $result ) )
{
echo $row["email"];
}
Otherwise, as Mike said you should use mysql_fetch_array()
ie.... this takes all the retrieved keys/fields and intereates them and hands them off to $s which can then be placed into html..
foreach($row as $key=>$val){
$$key = $val;
$s.= "<tr><td>".$key."</td><td>
<input type=text size=88 name='".$key."' value='".$val."'></td></tr>";
}
// end your php then onward to html
<table>
<?php echo $s;?>
</table>

PHP MySQL data FOR loop

<?php
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
$arrayResult = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
for ($x = 1; $x <= $num_rows; $x++){ //1st for loop
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
?>
$columns is an array entered by the user eg: $columns = array ('Column1', 'Column2', 'Column3);. These are the names of the columns which are in a given $table.
My idea was to create a function that displays the data from the MySQL table with the info from the $columns array. The problem is in the second for loop. The value of $i is reset every time the first loop is done, so I get the same result over and over again (the number of rows in the table).
My question is this: How do I keep the $i in the second loop from resetting?
Thank you in advance.
The reason you get the same result over and over is not because $i, but $arrayResult.
The right way is like this:
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while ($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
In your code you simple fetch always the first row and regardless of the subsequent cycles you only deal with that first row.
Just place
$arrayResult = mysql_fetch_array($result);
within the first loop just before echo '<tr>';
Anyway, for is not the best choice for iterating the records of a table, consider using while.
Why Dont you use while loop? If you use while you even don't need mysql_num_rows($result). Try this
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
I m sure, you will get your ans
Your code won't work ever. Because you didn't read manual entry for mysql_fetch_array()
There is no use for the for loops these days. You need some manual to see how to deal with loops in PHP. foreach and while you will need more often than for.
The idea of creating such a function is wrong. combining SQL and HTML in one function is a sign of VERY BAD design. What you really need is a function to get SQL data into array and a template.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$data = sqlArr("SELECT * FROM table");
include 'template.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $col): ?>
<td><?=$col?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
However, you can put this latter template code into function, if you're gonna use it often.
and call it like
<? drawTable($data) ?>

Categories