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

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

Related

output entire table of oracle DB in website with php and save as CSV

I am stuck at tryping to output an Oracle table with PHP on my website.
I can only output the row information in one line at the moment, other things fail and do not give me back anything or a parse error.
What I have:
<?php
set_time_limit(0);
$conn = oci_connect("name", "pw", "localhost/service_name");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['Error occured - no conenction created']), E_USER_ERROR);
$sql = 'SELECT * FROM VIEW_DFINVENTORY
WHERE ARTTIV NOT LIKE :didbv
AND ROWNUM <= 100
ORDER BY ARTID';
$stid = oci_parse($conn, $sql);
$didbv = 1;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['ARTID'] ."<br>\n";
echo $row['ARTCODE'] ."<br>\n";
This only gives me back the information like this:
ARTID
ARTCODE
ARTID
ARTCODE
ARTID
ARTCODE
...
the output with data:
13546987400
1234
1658198200R
1324
874312346AR
8792
...
How can I output the entire table/view as it is for example shown in SQLdeveloper or by outputting it to CSV with SQLPlus with all its headers and rows?
I looked around and found a loop that puts out in my case only a blank page on the browser:
<?php
set_time_limit(0);
$conn = oci_connect("name", "pw", "localhost/service_name");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['Error occured - no conenction created']), E_USER_ERROR);
$sql = 'SELECT * FROM VIEW_DFINVENTORY
WHERE ARTTIV NOT LIKE :didbv
AND ROWNUM <= 100
ORDER BY ARTID';
$stid = oci_parse($conn, $sql);
$didbv = 1;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
$results = array();
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
I am new to PHP so is there something I missed? I am really stuck and trying to fix this since over 12 hours now. Some sources are too advanced for me. Maybe you know a good tutorial for this. Every approach is welcomed.
I highly appreciate your help.
Thank you already in advance,
Matt
I'll use the second code example and add comments so you can see what actually happens :)
<?php
//...
/* oci_fetch_array returns you one row for the executed SQL-statement
* in each loop run $row contains one row/line of the table.
* $row always contains all selected columns (in your case * = all columns) of VIEW_DFINVENTORY
*/
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo "<tr>";
//you can now print out all relevant columns of one line (if you know the column name)
//or automatically all columns you have selected
foreach ($row as $columnName => $columnValue){
//print one data column
echo "<td>".$columnValue."</td>";
}
echo "</tr>";
}
Sometimes you maybe want the first row of the table containing all the column Names (=table header) then you should add this code before the while-loop
$columnsCount = oci_num_fields($stid);
echo "<tr>";
for ($i = 1; $i <= $columnsCount ; $i++) {
$colname = oci_field_name($stid, $i);
echo " <th>".htmlspecialchars($colname,ENT_QUOTES|ENT_SUBSTITUTE)."</th>";
}
echo "</tr>";

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

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.

Compare values of two tables and for results export JSON

I have two different tables. For those I select some results.
On the first based on a min/max and for the second based on Lat/Lng. That's easy (don't pay much attention on the values) and is created by:
$sql1="SELECT * FROM events WHERE value BETWEEN '".$min2d."' AND '".$max2d."'";
$sql2="SELECT * FROM locations WHERE (lng BETWEEN ".$wl." AND ".$el.") AND (lat BETWEEN '".$sl."'AND'".$nl."')";
Now that we have downsized the results, we want to match the 'id' row of the first table if exists on the second table. On success we create results.
So let's get some numbers first:
$result1 = mysql_query($sql1);
$result2 = mysql_query($sql2);
$numRows1 = mysql_num_rows($result1);
$numRows2 = mysql_num_rows($result2);
$loopCount1 = 1;
$loopCount2 = 1;
For more efficient parsing of the JSON (from a user) we want to sort the events by creating them into a JSON array with the location as a 'holder'. So that means, each location might have several events.
Some locations might not have events, but also some events might not correspond to a location. Our only comparing method is by the same 'id'.
With my following try, which is of course buggy creates for all (that's wrong) locations results even if for those without events. And that's where I need your precious help.
$json = '{"markers":[';
while ($row2 = mysql_fetch_array($result2)){
$json .= '{"coordinates": { "lat":'. $row2['lat'] .', "lng" : ' . $row2['lng'] .'},'
.'{"events" : [';
while ($row1 = mysql_fetch_array($result1)){
if ($row1['id']=$row2['id'])
$json .= '{ '
.'"title": "'.$row1['title'].'",'
.'"info": "'.$row1['info'].'",'
.'"}';
// add comma for Json if not final row
if ($loopCount1 < $numRows1) {
$json .= ', ';
$loopCount1++;}
}
$json .= ']}}';
// add comma for Json if not final row
if ($loopCount2 < $numRows2) {
$json .= ', ';
$loopCount2++;}
}
$json .= ']}';
And finally an echo:
echo $json;
To compare values of two tables and print results as json please use below code,
<?php
/* connect to the db */
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
mysql_select_db('db_name',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query1 = "SELECT * FROM test1";
$result1 = mysql_query($query1,$link) or die('Error query: '.$query1);
$query2 = "SELECT * FROM test2";
$result2 = mysql_query($query2,$link) or die('Error query: '.$query2);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result1) && mysql_num_rows($result2)) {
while($post1 = mysql_fetch_assoc($result1)) {
$post2 = mysql_fetch_assoc($result2);
if($post1['name'] == $post2['name'])
$posts[] = array('test1'=>$post1,'test2'=>$post2);
}
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
/* disconnect from the db */
#mysql_close($link);
?>

MySQL query limit part of query

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;

Categories