How Can I Limit the Output from a PHP While Loop? - php

I have a while loop running that is returning values from a MYSQL table. It returns about 90 entries from the query. My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify:
$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");
Here I am pulling the values out that I need from the table...
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
}
At this point, I have run the loop and get the display of all 90 entries. How can I pull the values out and display them in smaller chunks? If I use the looped values outside of the while loop, it just gives me the last value from the set. Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop?

This will add more br's and a hr after each 5 records:
$cnt = 0;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
if($cnt % 5 == 0) echo "<br><br><hr><br><br>";
$cnt++;
}

Here is one (not very sophisticated) approach you could take:
$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
if ($tracking_variable == 0) {
// logic for the start of a grouping
}
// logic to display the row
$tracking_variable = ($tracking_variable + 1) % $group_size;
if ($tracking_variable == 0) {
// logic for the end of a grouping
}
}
if ($tracking_variable > 0) {
// logic for the end of the final grouping
}

You want to save this data in a variable, and reference it outside of the loop.
Try this:
$data = array();
while($row=mysql_fetch_array($sql))
{
$data[$row['id']] = $row['column'];
}
And now you can just display specific rows:
print $data[$someRow];

Related

Pick a row with a specific index in a foreach loop

I want to output all image files of a specific productid. What is the right syntax to output the image path for row 1, row 2, row 3 etc? I can not find it.
$sql = "SELECT *
FROM images
WHERE productid = $productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
if($rs['imagepath']){
if($index == 0){
echo $imagepath[0]; // <---What is the right sytax of this?
}
}
if($rs['imagepath']){
if($index == 1){
echo $imagepath[1]; // <---and this?
}
}
if($rs['imagepath']){
if($index == 3){
echo $imagepath[2]; // <---and this?
}
}
The whole point of a foreach loop is it goes once through each select as "index". so you shouldn't have to worry about making an if-statement for each possible row, just make the statement once, and it will happen on each and every iteration
$rows = [];
$sql = "SELECT *
FROM images
WHERE productid = productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
$rows []= $rs;
}
echo $rows[0]['imagepath'];
aren't we missing the fetch function?
`
$select = $db->prepare($sql);
$select->execute(array());
$i = 0;
while($row = $select->fetch()) {
echo $i . ' '. $row['imagepath'] . '<br>';
$i++;
}
?>
`
--
addendum:
I now understand you only want one, or some, of the images to be shown.
Would it not be easier then, to only select that/those images?
SELECT imagepath
FROM images
WHERE productid = productid
AND someid = 3
or if no "someid" is present:
SELECT imagepath
FROM images
WHERE productid = productid
LIMIT 2,1
That would avoid the need to loop through may be 100 records to only use the 3th.

Submitting form values to database, php

I currently have a form that is built from an uploaded CSV. When the user uploads the CSV and hits 'Preview' Button it directs to a window that shows the entire CSV in a form table that is editable. The CSV is 5 records and 229 fields. The input names are built from row count and column count, so with this CSV it should start at row1col1 and go to row5col229.
I've discovered that the names are working like that, as expected, however I still have a problem. SOme of the CSV files will have 4 rows and some may have 8 or 9. I need to find a way to take the form input and submit it all into the 229 field staging table.
Is there a way to create an array and statement for one row and loop it for however many rows are actually present?
Here's my current code:
if(isset($_POST['preview']))
{
ini_set('auto_detect_line_endings', true);
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo '<form method="post">';
echo '<table>';
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
$colCount = 0;
echo '<tr>';
foreach($row as $value) {
echo "<td><input name='row".$rowCount."col".$colCount."' type='text' value='$value' /></td>";
$colCount++;
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
echo '<input type=\'submit\' value=\'Submit\' >';
var_dump($_POST);
echo '</form>';
}
?>
I feel like I'm on the right track but I have no idea how to go about building the array of elements or the statement so that it is a template, so to speak, and loop it for all rows.
In answer to the comments on the Answer by Tom:
You can set vales in the form into an array $_POST['rows']['columns'] ad then simply count($_POST['rows']); to count values and then foreach over each value in the row.
-- Martin
So I wouldn't need to go through and declare 229 elements? Just create the array and count, then loop with the foreach? In this case, how would I create a statement in SQL to insert to the database?
-- Tom
Your form would be an array of POST values such as
foreach($row as $value) {
echo "<td><input name='row[".$rowCount."][".$colCount."]' type='text' value='$value' /></td>";
$colCount++;
}
This will then produce an array POST value such as:
$_POST['row'][1][1] = $value;
$_POST['row'][1][2] = $value;
$_POST['row'][1][3] = $value;
...
$_POST['row'][1][229] = ...;
$_POST['row'][2][1] = ... ;
...
$_POST['row'][2][229] = ...;
...
$_POST['row'][5][229] = ...;
You can then run a foreach loop on this array and then extract the value of the data saved, for each key of the array:
$sql = $inserts = $binds = [];
foreach ($_POST['row'] as $rowValue){
if(is_array($rowValue) && count($rowValue) > 0 ){
foreach($rowValue as $rowData){
/***
* Stupidly, I had missed that row contains arrays
* rather than values, so you need a foreach, inside the
* foreach as so:
***/
foreach ($rowData as $columnKey => $columnValue){
//$columnValue will now equal $value
//$columnKey will be the column number (1...229)
/***
* This is the area you can construct your SQL query values.
* db_connection is assumed to be setup.
***/
$sql[] = "`column_name_".$columnKey."`"
$binder = "value".$columnKey;
$inserts[] = ":".$binder;
$binds[$binder] = $columnValue;
unset($binder);
}
unset($columnKey,$columnValue);
}
unset($rowData);
/***
* This is the area the SQL query is set on a per row basis
***/
$sqlFull = "INSERT INTO <table> (".implode(",",$sql).") VALUES(".implode(",",$inserts).")";
$db_connection->prepare($sqlFull);
/***
* EDIT: bind param MUST come after the prepare call
***/
foreach($binds as $bindKey=>$bindRow){
$db_connection->bind_param(":".$bindKey, $bindRow);
}
unset($bindKey,$bindRow);
$sql = $inserts = $binds = []; //reset arrays for next row iteration.
/***
* db_connection then executes the statement constructed above
***/
$db_connection->execute();
} //close if.
}
unset($rowValue);
Please note this a quick and dirty example only and I've not had time to check my syntax is exact, but it's more to give you a rough idea of the query structure
You can use count() to count the rows and columns in the $_POST array.
I actually figured this out, and The names are working as expected. However, I have an issue. Some CSV files will have 5 rows and some will have more, so I can't create a static way to do this by just input names. Is there a way to create one array and statement and loop it for however many rows are present?
EDIT
The current source code used for solving issues raised in comments to Martins answer.
<?
$connect = mysqli_connect($server, $user, $pw, $db);
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo'success!';
}
var_dump($_POST);
$sql = $inserts = $binds = [];
foreach ($_POST['row'] as $rowValue){
if(is_array($rowValue) && count($rowValue) > 0 ){
foreach($rowValue as $columnKey => $columnValue){
//$columnValue will now equal $value
//$columnKey will be the column number (1...229)
/***
* This is the area you can construct your SQL query values.
* db_connection is assumed to be setup.
***/
$sql[] = "`column_name_".$columnKey."`";
$binder = "value".$columnKey;
$inserts[] = ":".$binder;
$binds[$binder] = $columnValue;
unset($binder);
}
unset($columnKey,$columnValue);
/***
* This is the area the SQL query is set on a per row basis
***/
$sqlFull = "INSERT INTO staging (".implode(",",$sql).") VALUES(".implode(",",$inserts).")";
$connect->prepare($sqlFull);
/***
* EDIT: bind param MUST come after the prepare call
***/
foreach($binds as $bindKey=>$bindRow){
$connect->bind_param(":".$bindKey, $bindRow);
}
unset($bindKey,$bindRow);
var_dump($binds);
$sql = $inserts = $binds = []; //reset arrays for next row iteration.
/***
* db_connection is then given the SQL.
***/
$connect->execute();
echo "<p>\$sqlFull:<pre>".print_r($sqlFull,true)."</pre></p>\n";
if(mysqli_multi_query($connect, $sqlFull))
{
echo'File submitted';
} else {
echo "Error: " . mysqli_error($connect);
}
} //close if.
}
unset($rowValue);
?>

How can i stop a php while loop repeating over and over?

I have a polymer(1.0) app i am trying to create (based on stretch-tutorials league table), i cant figure out the routing if use mvc, so i have opted for the one page site, referencing different php files.
I Have a table in MYSql that i trying to incorporate into the table, using a simple echo table script, but this repeats itself hundreds of times. How can i stop this loop ?
$result = mysql_query('select * from results',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$sql = ('SELECT `home_team_name`,`away_team_name`,`home_goals_for`, `away_goals_for`, DATE_FORMAT(`fixture_date`, "%e %M %Y"), TIME_FORMAT(`fixture_time`, "%h:%i %p") FROM `results` ORDER BY fixture_date desc LIMIT 20 '.$table) or die('cannot show columns from '.$table);
echo '<h3>',$table,'</h3>';
$result2 = mysql_query($sql);
if(mysql_num_rows($result2)) {
echo '<table cellpadding="4" cellspacing="0" class="table table-striped table-hover table-bordered">';
echo '<tr class="info"><th>Home team</th><th>Away Team</th><th>Score</th><th>Score</th><th>Date<th>Time</th></tr>';
while($row2 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row2 as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
I have added ' < 50 ' but this returns 50 table header rows only ?
the site is live at http://jay-o.uk/#!/results the css and other data are okay for now, just this pesky loop.
Well.. maybe you need this code:
// Create an array
$items = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
/* print new insert */
var_dump('new item');
/* add a new item */
$items[] = array(
'home_team_name' => $row['home_team_name'],
'away_team_name' => $row['away_team_name'],
'home_goals_for' => $row['home_goals_for'],
'away_goals_for' => $row['away_goals_for']
);
}
$json_response = json_encode($items);
print $json_response;
If $json_response are a empty array maybe the problem is that the query don't return any row.
You need to set a "LIMIT" in the first query if you want to avoid a timeout operation, also i think that is posible to call a unique query that return all the info that you need but i don't know because your query is unintelligible.
Your code is wrong, the second query don't use the $table variable that is null value and what is de purpose to putting it after the limit parameter?
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 50');
if(mysql_num_rows($results)) {
print '<table>';
while ($row = mysql_fetch_row($results)) {
print '<tr>';
foreach ($row as $field_name => $field_value) print '<td>'.$field_value.'</td>';
print '</tr>'
}
print '</table>';
}
Sorry, the code is a bit messy, ive been working on this for a while and ifs frustrating, im not sure where i am going wrong, if i remove the $tableName variable i get an empty array, no matter what i do this is the results.
I have tried in json to no avail...
$db = mysql_connect($host,$user,$pass);
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db($db_name,$db);
$resulting = mysql_query("select * from results", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
$row_array['home_team_name'] = $row['home_team_name'];
$row_array['away_team_name'] = $row['away_team_name'];
$row_array['home_goals_for'] = $row['home_goals_for'];
$row_array['away_goals_for'] = $row['away_goals_for'];
//push the values in the array
array_push($json_response,$row_array);
$json = json_encode($json_response);
//echo $json;
$json_result = print_r((array) json_decode($json,true));
echo $json_result;
}
which leaves this: jay-o.uk/config/config.php
Could this be because i am referring to a view in mySql rather than a table ?
How about a simpler solution, just limit the query from the database to 1:
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 1');

How do I compare array value to the next value in array

I am wanting to compare the next value in the array with my current value. If you look at my code I think you will see what I am trying to do but to explain I need only one picture to show if $row[2] is the same on the next loop thru.
My error start at // ERROR HERE in if Statement in the code below.
I am sure there is a simple solution to this but I don't know the proper name and could not find it in my searches.
-Disclaimer I am still an newbie at this please forgive me.
$connection = mysqli_connect($host, $user, $pass, $db);
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// create query
$query = "SELECT * FROM 1098";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
echo "<center>";
// ERROR HERE in if Statement
$nextrow = 1 + $row;
if ( $row[2] <> $nextrow[2]){
if ( $row[6] == "kit"){
$img ='<img style="width: 700px; height: 800px;" alt="Picture Not Found" src=" ';
$file = substr($row[2], -3);
$filepath='files/'.$row[6].'/'.$file.'_files/image001.png">';
echo $img.$filepath;
}
else
{
$img ='<img style="width: 700px; height: 280px;" alt="Picture Not Found" src=" ';
$filepath='files/'.$row[6].'/'.$row[2].'_files/image001.png">';
echo $img.$filepath ;
}
}
echo "</center>";
}
}
$nextrow = 1 + $row doesn't make sense. That would be attempting to add an integer to a database record, i.e. 1 + array('foo', 'bar', 'baz').
If you simply want to compare the current record with the previous record (on all loops after the first one) how about something like this:
while($row = mysqli_fetch_row($result)) {
print '<center>';
// If there is no previous record set (first record) or if the 2nd value is different.
if (!isset($prev_record) || $prev_record[2] != $row[2]) {
// ...
}
print '</center>';
// Assign the current row to a variable so that it's available on the next run.
$prev_record = $row;
}
Edit – here's an example of how you can get all records into a single array and then play with them:
$records = array();
while($row = mysqli_fetch_row($result)) {
$records[] = $row;
}
foreach ($records as $i => $record) {
$record; // current record
$records[$i-1]; // last record
$records[$i+1]; // next record
}
I would recommend splitting your data up into multiple tables, though, and using a cleaner approach.
$nextrow = 1 + $row;
Given $row is a row, this is not doing what you think it is.
If you want the nextrow from the query you have to fetch it.
If you can reverse your logic to use previous row , you could preserve that and compare it to the current row.
You could read them all into an array first, but on a big result set that would be expensive....
You could do two fetches, one to current row, one to next row,
And then add a lot of logic to deal with the first and last, and making current = next and fetching the next next :(
Or you could rework the query so it returned the data you need in one row.
You definitely can't do what you are trying to do though. There is no next row until you fetch. $row is an array of columns, there is no rows as in an array of rows.

check a SQL query with if / else in PHP

I'm a complete novice in this but try to learn a lot by myself / tutorials. However I can not seem to find the answer to this (probably) easy problem. I want to check an output from my SQL database if it is smaller than 10 and then give me the current value of the INT. If it is not yet 10 or more then I want to output a line and if so output an other line. However, it does not seem to work properly at the moment.
//Connect to DB
$con = mysqli_connect("localhost","root","root","cursuson");
//Get counter!
$getcounter = mysqli_query($con,"SELECT * FROM cursus01");
$cursus01 = mysqli_fetch_assoc($getcounter);
//check if output is less than 10
if(count($cursus01) <= 10)
echo 'aantal aanmeldingen is ' . $cursus01['counter'] . '<br>';
else
echo 'De cursus gaat door! <br>';
//check the output
echo '<b>Aantal aanmeldingen:</b> ' . $cursus01['counter'] . '<br>';
echo '<b>ID:</b> ' . $cursus01['id'];
I assumed that you were trying to get the count of rows from the database (as others have done) and have left the answer for if that were the case below this one. You might find it useful and it seems like a waste to delete it!
Anyway, judging from your comment above and the $cursus01['counter'] in your question I'm now going to assume that what you actually want is the following...
Solution
I suggest that you use the mysqli method below as mysql will at some point in the near future be removed from the language as it is deprecated! If you continue to use it and create sites/apps with it then when this eventually happens you'll either have to use an old version of php which has it's own risks/limitations attached or face having a lot of broken code to fix...
mysql
mysql_connect("localhost","root","root");
mysql_select_db("cursuson");
$query = mysql_query("SELECT * FROM cursus01");
if(mysql_num_rows($query)){
//Rows are returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
if($row['counter'] <= 10){
//Counter is less than or exactly 10
}
else{
//Counter is greater than 10
}
}
}
else{
//No rows were returned
}
mysqli
$mysqli = new mysqli('localhost', 'root', 'root', 'cursuson');
$result = $mysqli->query("SELECT * FROM cursus01");
if($result->num_rows;){
//Rows are returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
if($row['counter'] <= 10){
//Counter is less than or exactly 10
}
else{
//Counter is greater than 10
}
}
}
else{
//No rows were returned
}
Original answer
I assume that you are actually trying to echo a count of the number of rows returned? Your current code echos a count of the number of coulmns. If you don't know already it would suggest that there are bigger problems here....
Solution
mysql
mysql_connect("localhost","root","root");
mysql_select_db("cursuson");
$query = mysql_query("SELECT * FROM cursus01");
$count = mysql_num_rows($query);
if($count <= 10){
//Less than (or exactly) 10 rows were returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
}
}
else if($count > 10){
//More than 10 rows were returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
}
}
else{
//No rows were returned
}
mysqli
$mysqli = new mysqli('localhost', 'root', 'root', 'cursuson');
$result = $mysqli->query("SELECT * FROM cursus01");
$count = $query->num_rows;
if($count <= 10){
//Less than (or exactly) 10 rows were returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
}
}
else if($count > 10){
//More than 10 rows were returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
}
}
else{
//No rows were returned
}
The way you're doing this, the count is going to be the same every time. You're count($cursus01) returns the number of columns in your database, to get the number of rows you should use the num_rows function or do a count query, unless you need the data from the query in which case you should do something like....
$cursus01 = array();
while($row = mysql_fetch_assoc($getcounter))
$cursus01[] = $row;
In this case count($cursus01) will return the number of rows. Hope i didn't confuse what you were asking. As edward pointed out you should start using mysqli instead of mysql. You also might want to look into using oop instead of procedural calls. see the manual for an example HERE
Agreed with Bryan answer, but when doing counts of database rows I'd choose the option of using MySQL count. In this case code line would be:
$getcounter = mysql_query("SELECT COUNT(*) FROM cursus01");
You will get the exact number of rows using this query
I assume you want to count the number of records stored in the table.
use mysqli_num_rows() function instead of count().
$con = mysqli_connect("localhost","root","root","cursuson");
$getcounter = mysqli_query($con,"SELECT * FROM cursus01");
$row = array();//create an empty array
//check if output is less than 10
if(mysqli_num_rows($getCounter) <= 10):
$row = mysqli_fetch_array($getCounter);
echo $row['counter']."<br>";
else:
echo 'De cursus gaat door! <br>';
endif;
//display the output
echo '<b>Aantal aanmeldingen:</b> ' . $row['counter'] . '<br>';
echo '<b>ID:</b> ' . $row['id'];

Categories