how to display result of query - php

After query I try to display data. I can receive only data from 'field_1[]'. From 'field_2[]' and from 'field[]' no. How to fix it?
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_rows($result);
//------------------------------------------------------------------
for($i_1=0; $i_1<$fields_num; $i_1++)
{
$field_1 = mysql_fetch_assoc($result);
echo "<td>a".$field_1['index_period_1']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_assoc($result);
echo "<td>b".$field['index_period']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i_2=0; $i_2<$fields_num; $i_2++)
{
$field_2 = mysql_fetch_assoc($result);
echo "<td>c".$field_2['index_period_2']."</td>";
}
edit:----------------------
|------------|period_1 |period_1 |period_1 |
-----------------------------------------------
|period_2 |period |period |period |
-----------------------------------------------
|period_2 |period |period |period |
-----------------------------------------------

You are sort of missing the point of mysql_fetch_assoc() and rows in MySQL:
while ($row = mysql_fetch_assoc($result)) {
echo $row['index_period'];
echo $row['index_period_1'];
echo $row['index_period_2'];
}
You call mysql_fetch_assoc() once per row.
I'm not really sure why you need to loop over your table like this, but I won't interrogate you.
This might fit your needs (I cringe writing this):
$index_period = array();
$index_period_1 = array();
$index_period_2 = array();
while ($row = mysql_fetch_assoc($result)) {
$index_period[] = $row['index_period'];
$index_period_1[] = $row['index_period_1'];
$index_period_2[] = $row['index_period_2'];
}
foreach ($index_period as $value) {
echo "<td>a" . $value . "</td>";
}
foreach ($index_period_1 as $value) {
echo "<td>b" . $value . "</td>";
}
foreach ($index_period_2 as $value) {
echo "<td>c" . $value . "</td>";
}

Once you finish your first for loop, you have iterated through the entire result set. So when you enter your next for loop, there is nothing left to iterate and mysql_fetch_assoc() returns false. If you want to reset the internal data pointer, you can call
mysql_data_seek($result, 0);
This will enable you to re-iterate through the result set in your next for loop.

Related

identifying column number in PHP mysqli_fetch_row() WHILE loop

I'm trying to identify whether I am looking at the first column in the array.
I haven't tried anything, but googled plenty and cannot find a solution.
while($row = mysqli_fetch_row($sql)) {
echo '<tr>';
foreach ($row as $col) {
if () //NEED CODE HERE
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
echo '</tr>';
}
mysqli_fetch_row fetches "one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero)." So the key of the column is the same as column order.
So you can do this:
while($row = mysqli_fetch_row($sql)) {
echo '<tr>';
foreach ($row as $key => $col) {
if ($key === 0) {
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
}
echo '</tr>';
}
But column is subjected to changes in database structure and SQL query changes. I would personally prefer mysqli_fetch_assoc or mysqli_fetch_object so I can use the column by name instead of order number. Its less error prone. For example,
while($row = mysqli_fetch_assoc($sql)) {
echo '<tr>';
foreach ($row as $key => $col) {
if ($key === 'ip_address') {
echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
}
}
echo '</tr>';
}
Note: $sql here should be a mysqli_query result instead of the actual SQL string.

PHP trying to add values to an array in a while loop

I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.

How can I re-organize php array of sports

I'm trying to list sport league offerings for intramurals. My current php foreach spits out all the leagues and offerings. Great.
Now I want to only show 1 instance of the sport (course), like "Basketball" and then list the multiple league offerings (offering) in columns.
I can't do another loop based on
if $nt['course'] == "Basketball" because these will change
Not sure if my mssql query needs to change or if I can use another foreach loop?
query
$sql2 = SELECT category
,course
,offering
,Semester
,spots
,registerLink from dbtable WHERE semester like "%Fall 2016%" and category like "%Leagues%" ORDER BY course
$rs= mssql_query ($sql2, $con)
or die("Error!");
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
$result[] = $row;
}
}
return $result;
exit();
my foreach loop in view:
<?php
foreach ($data as $nt) {
echo "<div class='col-md-2'>";
echo "<h2><a href='#'>".$nt['course']."</a></h2>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
So just to clarify:
category = "Leagues" which is in my query
course = Basketball and Flag Football, etc
It's very simple:-
instead of
$result[] = $row;
do
$result[ $row['course']][] = $row;
Simple solution:
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
if(!in_array($row["course"], $result))
{
array_push($result, $row["course"]);
}
array_push($result[$row["course"]], $row);
}
}
return $result;
And loop in view:
foreach($data as $key => $value)
{
echo "<h1>".$key."</h1>";
foreach($value as $nt)
{
echo "<div class='col-md-2'>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
}

php for each in while loop

I am trying to get specific data from a while loop and loop it x number of times.
I'm selecting this data:
$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'");
while ($adData = mysql_fetch_array($r, MYSQL_NUM))
{
$data = $adData;
$ac0 = $data['ac0'];
$ac1 = $data['ac0'];
print $ac0;
print $ac1;
}
This doesn't work. Nothing gets printed out.
What I want to do is to get ac6 to ac0 value for that specific advertisement (where token).
How can I do that?
Change your numeric fetch to an associative one, then add a foreach loop to process the result.
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
while ($adData = mysql_fetch_assoc($r))
{
foreach ($adData as $key => $value)
{
$nubmer = (int)substr($key, 2);
print $value; // or whatever you actually want to do
}
}
Also I hope you're validating $_GET['token'] against possible mischief in your code.
You can create an arrays to add the values from the result query
1st is to create an array:
$advert_AC0 = array();
$advert_AC1 = array();
$advert_AC2 = array();
$advert_AC3 = array();
$advert_AC4 = array();
$advert_AC5 = array();
$advert_AC6 = array();
Now, to add content to array
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result
while ($adData = mysql_fetch_assoc($r))
{
array_push($advert_AC0, $dData['ac0']);
array_push($advert_AC1, $dData['ac1']);
array_push($advert_AC2, $dData['ac2']);
array_push($advert_AC3, $dData['ac3']);
array_push($advert_AC4, $dData['ac4']);
array_push($advert_AC5, $dData['ac5']);
array_push($advert_AC6, $dData['ac6']);
}
}else{
echo "NO RESULT.";
}
to call for the array values, 1 by 1
$count_array = count($advert_AC0);
$i = $count_array;
while(1 <= $i){
echo "AC0: $advert_AC0[$i]<br>";
echo "AC1: $advert_AC1[$i]<br>";
echo "AC2: $advert_AC2[$i]<br>";
echo "AC3: $advert_AC3[$i]<br>";
echo "AC4: $advert_AC4[$i]<br>";
echo "AC5: $advert_AC5[$i]<br>";
echo "AC6: $advert_AC6[$i]<br>";
$i++;
}
I don't know if my answer solved your question, please comment if not.

If a row is not unique - ignore it - php

I'm working on the following code:
function form_Subcat_Picker() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$catPicker = "SELECT Subcatid, Subcatname, Parentid
FROM ProductSubCats
ORDER BY Subcatid";
if ($Result = $mysqli->query($catPicker)){
if (!$Result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
}
}
$mysqli->close();
}
What I want to do, is in the line:
while ($row = $Result->fetch_assoc()) {
echo '<div class="parentid'.$row['Parentid'].'">';
If the $row['Parentid'] part is the same as the previous iteration, I want to ignore that particular line (adding the div class)
So that if for example in the first run $row['Parentid'] is 1, and in the next loop it is 1 again, I want to not create a new div, just echo everything else and thus keep it in the same div.
Is this possible? Alternatively, how could I make multiple sub category id's and names appear in the one div, if they share a common parentid (there are multiple parent ids)
For the line:
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
Maybe this would work:
$last_id = 0;
while ($row = $Result->fetch_assoc()) {
if ($last_id != $row['Parentid']) {
echo '<div class="parentid'.$row['Parentid'].'">';
echo '<select name="Subcatid">';
echo '<option value="'.$row["Subcatid"].'">'.$row["Subcatname"]."</option>";
echo '</select>';
echo '</div>';
$last_id = $row['Parentid'];
}
}
However, I think the best solution is to filter them out in the SQL statement, maybe the GROUP BY clause, but I'm not 100% sure how to do it :).
Regards,
That is just something basic for looping. Let's see your current loop:
while ($row = $Result->fetch_assoc()) {
...
}
As you want to skip with a specific condition, let's just introduce this skipping (not taking much care about the condition first):
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
}
Now let's formulate the condition. As we want to look into the last $row we need to keep a copy:
$last = null;
while ($row = $Result->fetch_assoc()) {
if ($condition) continue;
...
$last = $row;
}
Now we've got the data we need to have to create the condition, $last can contain the last row (if there was one) and therefore the comparison can be done:
$last = null;
while ($row = $Result->fetch_assoc()) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
$last = $row;
}
And that is it basically. Depending on the logic, you might want to switch to a for loop:
for ($last = null; $row = $Result->fetch_assoc(); $last = $row) {
$condition = $last && $row['Parentid'] === $last['Parentid'];
if ($condition) continue;
...
}
This for example does ensure that for each iteration (even the skipped ones), the $last is set to the $row at the end of the loop.
Instead of continue you can naturally do different things, like not outputting the <div> or similar.
Hope this helps.
This is the way I'd write it.
// add a variable to hold the previous value
$previous_parent_id = "";
while ($row = $Result->fetch_assoc()) {
// then add an if statement to see if it's the previous statement
if ($row['parent_id'] != $previous_parent_id){
echo '<div class="parent_id'.$row['parent_id'].'">';
$previous_parent_id = $row['parent_id'];
}
}
So going in a loop on these records
ID ParentID
1 0
2 0
3 1
4 1
4 2
4 2
the output would be:
<div class="parent_id0">
<div class="parent_id1">
<div class="parent_id2">

Categories