If a row is not unique - ignore it - php - 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">

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.

Making an Array from Database MySQL

I have database connection. I want to make an array but something is problem i think. Here is my array code:
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
foreach ($result as $row) {$data[] = $row;}
print_r($data);
$no=1;$total_deger=count($data);
echo $total_deger;
for($i=0;$i<$total_deger);$i++){
$xxx[i]="[Date.UTC(".$data[i]['year'].",".$data[i]['month'].",".$data[i]['day'].",".$data[i]['saat'].",".$data[i]['dakika'].",00),".$data[i]['Guc']."]";if($no < $total_deger){echo ",";}
echo $xxx[i];
}
When I run this code, nothing happens in page. When I write to for example 0 for i. I can see my array value. Where do I mistake?
Code with correction and suggestion (both are commented):-
<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1);// display those errors
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) { // check you got results or not
while($row = $result->fetch_assoc()) {
$data[] = $row; // assign them
}
}
//foreach ($result as $row) {$data[] = $row;} // not needed
print_r($data);
$no=1;
$total_deger= count($data);
echo $total_deger;
for($i=0;$i<$total_deger;$i++){ // remove )
$xxx[$i]="[Date.UTC(".$data[$i]['year'].",".$data[$i]['month'].",".$data[$i]['day'].",".$data[$i]['saat'].",".$data[$i]['dakika'].",00),".$data[$i]['Guc']."]"; // use $i instead of i
if($no < $total_deger)
{
echo ",";
}
echo $xxx[$i];
}
Note:- Always add some error reporting code. So that all errors will populated and you can rectify those
Also better would be to use foreach() instead of for loop (as it will take care of indexes itself):-
//use foreach
foreach ($data as $dat){
echo "[Date.UTC(".$data['year'].",".$data['month'].",".$data['day'].",".$data['saat'].",".$data['dakika'].",00),".$data['Guc']."]";
}
Firstly you want to check your SQL query returns rows. Then I think you need to modify your foreach to a while as below. Also checking that rows are returned before looping.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
As per example given here: http://www.w3schools.com/php/php_mysql_select.asp

Removing Last Comma within while loop - PHP

I've been building a little tool to manage a dataset, I'm trying create a JSON output in order to serve my front-end the data.
Right now I have an extra comma at the end of every row in the loop. I need to remove it, it would be ideal if I can find a way to do this inside of the while loop.
Here is my code:
$sth = mysql_query("SELECT * FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
if (++$counter == $num_rows) {
echo json_encode($r) . '';
}
else {
echo json_encode($r) . ',';
}
}
echo "]";
mysql_close($connection);
This is what I'm getting returned now
[
{"col1":"123","col2":"456","col3":"789",},
{"col1":"123","col2":"456","col3":"789",}
]
This is what I need.
[
{"col1":"data1","col2":"data2","col3":"data3"},
{"col1":"data1","col2":"data2","col3":"data3"}
]
Any suggestions would be greatly appreciated.
Your whole approach is wrong, you shouldn't try to create JSON by hand. Put all the rows in an array, and let json_encode() do it all for you.
$result = array();
while ($r = mysql_fetch_assoc($sth)) {
$result[] = $r;
}
echo json_encode($result);
I like to follow best practice whereever possible, but in this particular instance I needed to deviate from best practice due to some environment restrictions I had. I thought I'd share the solution I ended up using, regardless of it being overly complicated.
$sth = mysql_query("SELECT name,address,address2,city,state,postal,phone,lat,lng FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
if (++$counter == $num_rows) {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)));
}
else {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)) . ',');
}
}
echo "]";
mysql_close($connection);

how to display result of query

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.

Categories